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

后端 未结 4 1407
猫巷女王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:39

    I can contribute a 50% solution. 50% because it seems to be not easy to wrap Query Methods. Also custom JPA queries are an issue for this global approach. If the standard finders are sufficient it is possible to extend an own SimpleJpaRepository:

    public class CustomJpaRepositoryIml extends
        SimpleJpaRepository {
    
    private JpaEntityInformation entityInformation;
    
    @Autowired
    public CustomJpaRepositoryIml(JpaEntityInformation entityInformation,
                                  EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.entityInformation = entityInformation;
    }
    
    
    
    private Sort applyDefaultOrder(Sort sort) {
        if (sort == null) {
            return null;
        }
        if (sort.isUnsorted()) {
            return Sort.by("insert whatever is a default").ascending();
        }
        return sort;
    }
    
    private Pageable applyDefaultOrder(Pageable pageable) {
        if (pageable.getSort().isUnsorted()) {
            Sort defaultSort = Sort.by("insert whatever is a default").ascending();
            pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), defaultSort);
        }
        return pageable;
    }
    
    
    @Override
    public Optional findById(ID id) {
        Specification filterSpec = filterOperatorUserAccess();
        if (filterSpec == null) {
            return super.findById(id);
        }
        return findOne(filterSpec.and((Specification) (root, query, criteriaBuilder) -> {
            Path path = root.get(entityInformation.getIdAttribute());
            return criteriaBuilder.equal(path, id);
        }));
    }
    
    @Override
    protected  TypedQuery getQuery(Specification spec, Class domainClass, Sort sort) {
        sort = applyDefaultOrder(sort);
        Specification filterSpec = filterOperatorUserAccess();
        if (filterSpec != null) {
            spec = (Specification) filterSpec.and((Specification) spec);
        }
        return super.getQuery(spec, domainClass, sort);
    }
    
    }
    

    This implementation is picked up e.g. by adding it to the Spring Boot:

    @SpringBootApplication
    @EnableJpaRepositories(repositoryBaseClass = CustomJpaRepositoryIml.class)
    public class ServerStart {
    ...
    

    If you need this kind of filtering also for Querydsl it is also possible to implement and register a QuerydslPredicateExecutor.

提交回复
热议问题