Skip to content

Query-by-example skip primitives?

Spring supports creating queries by examples of the object to look for. Like:

//if not setting the age, it will always look for age=0
Person p = new Person();
List<Person> foundPersons = personRepository.findAll(Example.of(p));

public class Person {
  private String firstName;
  private String lastName;
  private LocalDate dob;
  private int age;

Problem: if the @Entity has primitive fields, then their default value will actually be used for creating the query. The example above will result in:

SELECT * from persons where lastname := 'Smith' and age := 0

In my example I have a database field where age must always be filled, thus is not allowed to be null. Therefore the entity has a primitive int age field.

Of course I could now change the field to Integer age, but then I’d marking the field being an optional nullable attribute, which is not true.

So, how can I skip primitives that have not been set on the Example?

Reference Example



Yes, you can do it:

Person p = new Person();

Example criteria = Example.create(p).setPropertySelector(
List<Person> foundPersons = session.createCriteria(Person.class).add(criteria).list();

Example.NotNullOrZeroPropertySelector.INSTANCE is a property selector that includes only properties that are not null and non-zero (if numeric)


Above an example for Hibernate org.hibernate.criterion.Example class. For you can ignore primitive fields by manually specifying names of these fields:

Person p = new Person();

ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("age").withIgnoreNullValues();

Example criteria = Example.of(p, matcher);
List<Person> foundPersons = personRepository.findAll(criteria);
4 People found this is helpful