Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA Query By Example Match One Null Field but Ignore Others

When querying by Example with JPA, is there a way to specify null matching for one column instead of all? It seems like the Null matching can only be applied to all columns.

class Entity {
  private Integer id;
  private String name;
  private Instant createdAt;
  private Instant deletedAt;
  // getters and setters
}

When querying by example, I want to include when deletedAt is actually null in the example, but ignore the null matching on other fields. In the database, the created_at column is a TIMESTAMP WITHOUT TIME ZONE column (postgresql)

Edit: Solutions proposed in Spring data query where column is null aren't applicable since they don't take advantage of querying by example

like image 693
aarbor Avatar asked Dec 04 '25 21:12

aarbor


1 Answers

You can try achieve what you want with ExampleMatcher. Specifically ExampleMatcher.includeNullValues() and / or ExampleMatcher.withIgnorePaths("deletedAt")

Try one or both:

ExampleMatcher exampleMatcher = ExampleMatcher.matchingAll()
                                               .withIgnorePaths("deletedAt")
                                               .withIncludeNullValues();
Example<Entity> ex = Example.of(obj, exampleMatcher);
like image 194
Robert Niestroj Avatar answered Dec 07 '25 10:12

Robert Niestroj