0

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 = ? )
Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
touchchandra
  • 1,506
  • 5
  • 21
  • 37
  • JPA generally doesn't support union[some providers might]; have you tried the last query in proper form, what exception you are getting, incorrect results, no results, query not parsing etc. – Nayan Wadekar Nov 28 '16 at 06:30
  • Possible duplicate of [Spring data jpa - How to combine multiple And and Or through method name](https://stackoverflow.com/questions/35788856/spring-data-jpa-how-to-combine-multiple-and-and-or-through-method-name) – Jens Schauder Jun 24 '19 at 05:08

1 Answers1

1

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/

Avinash
  • 4,115
  • 2
  • 22
  • 41