I got this working by using custom repository. There is no straightforward way the kind you are expecting as far as I know. Following is what I did on a Comment
entity given below.
@Entity
@FilterDef(name="filterByEmail", parameters={@ParamDef(name="email", type="string")})
@Filters( {
@Filter(name="filterByEmail", condition=":email = email")
} )
public class Comment {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
private String email;
}
Defined a Repository as follows
@Repository
@Transactional
public interface CommentRepository extends CrudRepository<Comment, Long>,CommentRepositoryCustom {
}
In the custom repository get a handle on the EntityManager
and enable session.
public class CommentRepositoryImpl implements CommentRepositoryCustom{
@PersistenceContext
private EntityManager entityManager;
@Autowired
private CommentRepository commentRepository;
@Override
public Iterable<Comment> findCommentWithEmail(String email) {
Filter filter = (Filter)entityManager.unwrap(Session.class).enableFilter("filterByEmail");
filter.setParameter("email", "arun.menon");
Iterable<Comment> iterable = commentRepository.findAll();
entityManager.unwrap(Session.class).disableFilter("filterByEmail");
return iterable;
}
}
Following is the Test executed.
public void run(String... arg0) throws Exception {
Iterable<Comment> iterable = commentService.findCommentWithEmail("test@test.com");
System.out.println("User ois" + iterable);
}
If you need a more generic kind of solution refer here.