Search code examples
springspring-data-jpaspring-datajparepository

How do I implement a Criteria API method along with JpaRepository interface? (Spring Boot)


I need to implement one more method to my JpaRepository, but this one has many criterias and I would like to use Criteria API. But I can`t browse, how to do it in elegant way. So my question is in other words: Could I add a method to my JpaRepository interface and implement it somehow, to use it like generated methods?

I tried to implement this repo interface, but compiler makes me implement all methods.


Solution

  • If you want to use criteria in JPA you can go with JPA Specification/Predicates.

    As you can add multiple conditions to it in your repository and return the expected results.

    for example - under your service layer call a JPA method naming anything you want and pass the argument to it if you want to.

    like :-

    (result is in list case) - Service layer

    List<your Generic> list = yourRepository.yourMethodName(your Argument);
    

    Repository layer

    default List<your Generic> yourMethodName(your Argument session) {
            return findAll(new Specification<your Generic>() {
                private static final long serialVersionUID = 1L;
    
                @Override
                public Predicate toPredicate(Root<your Generic> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicates = new ArrayList<>();
    
                    //your condition will be here-------
                    //for example --
                    if (session.getUserType().equalsIgnoreCase("ADMIN")) {
                        predicates.add(
                                criteriaBuilder.and(criteriaBuilder.equal(root.get("userLevel"), 3)));
    
                        predicates.add(criteriaBuilder
                            .and(criteriaBuilder.equal(root.get("isActive"), "Yes")));
                    }
                    
                    //and many more conditions you can use here to get the expected data... like and, or, like, ge, equal, etc...
                    return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            });
        }
    

    for different criteria queries you can refer - https://www.baeldung.com/spring-data-criteria-queries

    https://www.baeldung.com/jpa-and-or-criteria-predicates

    if still any issue please let me know down in the comment