touchchandra
touchchandra

Reputation: 1556

In Spring Data JPA how to achieve Where predicate with AND and OR together

using JapRepository - SPring Data JPA, how to handle this case : (AnB) U (CnD) operation where braces plays vital role.

findAllByAAndB() => WHERE A = ? AND B = ?
findAllByCAndD() => WHERE C = ? AND D = ? 
findAllByXOrY() => WHERE X = ? AND Y = ?
<How to achieve this clause> => WHERE  ( A = ? AND B = ? ) OR ( C = ? AND D = ? )

Upvotes: 0

Views: 1738

Answers (1)

Avinash
Avinash

Reputation: 4279

In such scenario you can use JpaSpecificationExecutor, following is the way to implement.

  1. Extend your repo with JpaSpecificationExecutor.

    public interface EntityRepo extends PagingAndSortingRepository<Entity, String>, JpaSpecificationExecutor<Entity>

  2. Create a Specification class and implement your query using Predicate

    Predicate predicateAnd1 = cb.equal(entity.getA(), entity.getB());

    Predicate predicateAnd2 = cb.equal(entity.getC(), entity.getD());

    Predicate predicateOr = criteriaBuilder.and(predicateAnd1, predicateAnd2);

  3. Then in your service class use something like following

    repo.findAll(entitySpec.getSpec());

The following page has a good example.

https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

Upvotes: 1

Related Questions