Robson Braga
Robson Braga

Reputation: 342

Spring Query By Example using "OR"

I have a JPA entity that has two attributes to search by "OR" operator instead of "AND". Those are ledgerCode and division:

Company comp = new Company();
ExampleMatcher matcher =
    ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING)
        .withIgnoreCase("name");

comp.setCountryCode(countryCode);
comp.setLedgerCode(ledgerCode);
comp.setDivision(division);
comp.setName(name);

List<Company> result = compSearchRepository.findAll(Example.of(comp, matcher));

Then the SQL result should be (supposing all the parameters not null):

SELECT d 
  FROM COMPANY d 
 WHERE d.countryCode = country 
    OR d.ledgerCode = ledger 
    OR d.division = division 
   AND lower(d.name) LIKE '%name%'

Is it possible? If yes, how so? I couldn't find any code example on Google nor a suggestive method name in ExampleMatcher class.

Upvotes: 5

Views: 4796

Answers (1)

Daniel K&#228;fer
Daniel K&#228;fer

Reputation: 4704

You can't combine a OR and AND search with Query By Example.

With the methode ExampleMatcher.matchingAny() a OR operation is generated instad of a AND operation. But this operation is used for every attribute.

Upvotes: 5

Related Questions