How to add global where clause for all find method

2019-02-19 11:18发布

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 (Spring Data methods) will have to be checked with the compid.

I need a way that, this "where compid = ?" check to be injected automatically for every find method. So that we won't have to specifically bother about compid checks.

Is this possible to achieve from Spring Data JPA framework?

3条回答
相关推荐>>
2楼-- · 2019-02-19 11:25

May be Hibernate‘s annotation @Where will help you. It adds a given condition to any JPA queries. For example

@Entity
@Where(clause = "isDeleted='false'")
public class Customer {
    //...
    @Column
    private Boolean isDeleted;
}

More info: 1, 2

查看更多
三岁会撩人
3楼-- · 2019-02-19 11:38

Like other people have said there is no set method for this

One option is to look at Query by example - from the spring data documentation -

Person person = new Person();
person.setFirstname("Dave");
Example<Person> example = Example.of(person); 

So you could default compid in the object, or parent JPA object

Another option is a custom repository

查看更多
Ridiculous、
4楼-- · 2019-02-19 11:48

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<YourEntity> l = someRepository.findAllWithNamesLike("test");
    } 

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

查看更多
登录 后发表回答