How to add global where clause for all find methods of Spring data JPA with Hibernate?

后端 未结 4 1406
猫巷女王i
猫巷女王i 2020-12-19 10:00

We are working on web application using Spring data JPA with hibernate.

In the application there is a field of compid in each entity. Which means in every DB call (S

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 10:58

    Agree with Abhijit Sarkar.

    You can achieve your goal hibernate listeners and aspects. I can suggest the following : create an annotation @Compable (or whatever you call it) to mark service methods create CompAspect which should be a bean and @Aspect. It should have something like this

    @Around("@annotation(compable)")`
        public Object enableClientFilter(ProceedingJoinPoint pjp, Compable compable) throws Throwable {
            Session session = (Session) em.getDelegate();
            try {
                if (session.isOpen()) {
                    session.enableFilter("compid_filter_name")
                            .setParameter("comp_id", your_comp_id);
                }
                return pjp.proceed();
            } finally {
                if (session.isOpen()) {
                    session.disableFilter("filter_name");
                }
            }
        }
    
    em  - EntityManager
    

    3)Also you need to provide hibernate filters. If you use annotation this can look like this:

    @FilterDef(name="compid_filter_name", parameters=@ParamDef(name="comp_id", type="java.util.Long"))
    @Filters(@Filter(name="compid_filter_name", condition="comp_id=:comp_id"))
    

    So your condition where compid = ? will be @Service method below

       @Compable
        someServicweMethod(){
         List l = someRepository.findAllWithNamesLike("test");
        } 
    

    That's basically it for Selects, For updates/deletes this scheme requires an EntityListener.

提交回复
热议问题