Let's say I have an entity class like this (minimal code for brevity):
@Entity
public class Thing {
private Long groupID;
private String name;
private String description;
}
Requirement is to implement a search for a String value present in either name
or description
, for Thing
s with a specific groupID
. I'd try writing a Spring Data JPA "derived" query method like one of these:
public ThingRepo extends JpaRepository<Thing, Long> {
public Collection<Thing> findByGroupIDAndNameContainsOrDescriptionContains(Long groupID, String name, String description);
public Collection<Thing> findByNameContainsOrDescriptionContainsAndGroupID(String name, String description, Long groupID);
}
To search for the same text in either name
or description
, I'd pass that same value for both method arguments. However, neither of these produces the expected results, because of how Spring Data processes the logical And
and Or
operators in the method name - I can't find any way to group the name
and description
criteria with logical Or
.
Is there a way to implement a query method like this without resorting to JPQL and @Query
?
findByGroupIDAndNameContainsOrDescriptionContains(...)
evaluates to (A∧B)∨C
but if I understood correctly you want
A∧(B∨C)
which is equivalent to (A∧B)∨(A∧C)
, so it should be
public Collection<Thing> findByGroupIdAndNameContainsOrGroupIdAndDescriptionContains(Long groupId1, String name, Long groupId2, String description)
where name=description
and groupId1=groupId2
.