如何解决Spring Data JPA:通过示例查询?
Spring数据依赖于JPA和EntityManager,而不依赖于Hibernate和Session,因此,你没有开箱即用的findByExample。你可以使用spring数据自动查询创建,并使用以下签名在存储库中编写一个方法:
List<Person> findByEmployedAndLastNameAndDob(boolean employed, String lastName, LocalDate dob);
Person person = new Person();
person.setLastname("Smith");
Example<Person> example = Example.of(person);
List<Person> results = personRepository.findAll(example);
请注意,这需要最新的2016版本
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.12.1.RELEASE</version>
</dependency>
解决方法
使用Spring Data JPA可以通过示例进行查询,其中将特定的实体实例用作搜索条件?
例如(如果没有双关语),如果我有一个Person
看起来像的实体:
@Entity
public class Person {
private String firstName;
private String lastName;
private boolean employed;
private LocalDate dob;
...
}
我可以找到所有以1977年1月1日出生的姓Smith的受雇人员为例:
Person example = new Person();
example.setEmployed(true);
example.setLastName("Smith");
example.setDob(LocalDate.of(1977,Month.JANUARY,1));
List<Person> foundPersons = personRepository.findByExample(example);