按示例查询跳过原语?

时间:2017-08-04 10:57:04

标签: java spring spring-data-jpa

Spring支持通过要查找的对象的示例创建查询。像:

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

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

问题:如果@Entity有原始字段,那么它们的默认值实际上将用于创建查询。上面的例子将导致:

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

在我的示例中,我有一个数据库字段,其中age必须始终填充,因此不允许null。因此,该实体具有原始int age字段。

当然我现在可以将字段更改为Integer age,但之后我将字段标记为可选的可空属性,这不是真的。

那么,我如何跳过尚未在Example上设置的原语?

Reference Example

2 个答案:

答案 0 :(得分:5)

Yes, you can do it:

Person p = new Person();
p.setLastName("Smith");

Example criteria = Example.create(p).setPropertySelector(
    Example.NotNullOrZeroPropertySelector.INSTANCE
);
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)

UPD

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

Person p = new Person();
p.setLastName("Smith");

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

Example criteria = Example.of(p, matcher);
List<Person> foundPersons = personRepository.findAll(criteria);

答案 1 :(得分:0)

在Spring引导中,我将原始值设为0。因此,我已按以下方法解决

     ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("parentId");//ignore primitives
     Example<ConfigMetadata> configExample = Example.of(config, matcher);
     if(config.getParentId()!=null && config.getParentId() != 0) { //if primitives other than null/zero, create new example which includes them
        configExample.getProbe().setParentId(config.getParentId());
        configExample = Example.of(configExample.getProbe());
     }