Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filters For Spring Data + JPA

Is there any way to define generic filters for Spring data repositories that allow filtering out data, similar to what is available with Hibernate? As an example it would be cool if I could do something like this:

@FilterDef(name = "clientSecurity", defaultCondition = "clientId in (:allowableClients)", parameters = { @ParamDef(name = "allowableClients", type = "Long") })
public interface DocumentRepository extends Repository<Document, Long> {
    public List<Document> findAll();
}

So in the above example, my document repository would only return all documents that belong to client in the set of allowable client ids.

like image 900
timmy Avatar asked May 25 '15 01:05

timmy


Video Answer


1 Answers

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("[email protected]");
    System.out.println("User ois" + iterable);
}

If you need a more generic kind of solution refer here.

like image 64
ArunM Avatar answered Sep 18 '22 18:09

ArunM