Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA: Query by Example?

Using Spring Data JPA can I do a query by example where a particular entity instance is used as the search criteria?

For example (no pun intended), if I have a Person entity that looks like:

@Entity public class Person {   private String firstName;   private String lastName;   private boolean employed;   private LocalDate dob;   ... } 

I could find all employed persons with a last name of Smith born on January 1, 1977 with an example:

Person example = new Person(); example.setEmployed(true); example.setLastName("Smith"); example.setDob(LocalDate.of(1977, Month.JANUARY, 1)); List<Person> foundPersons = personRepository.findByExample(example); 
like image 337
Brice Roncace Avatar asked Dec 23 '14 19:12

Brice Roncace


People also ask

What is query by example in Spring data JPA?

Spring Data JPA Query By Example Query by Example (QBE) is a user-friendly querying technique with a simple interface. It allows dynamic query creation. We do not need to write queries with store-specific query language. We work with three objects.

How do we execute a normal SQL query in Spring data JPA?

Select Query In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.

How do I write a JPA query?

Creating SQL QueriesAdd a query method to our repository interface. Annotate the query method with the @Query annotation, and specify the invoked query by setting it as the value of the @Query annotation's value attribute. Set the value of the @Query annotation's nativeQuery attribute to true.


1 Answers

This is now possible with Spring Data. Check out http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example

Person person = new Person();                          person.setLastname("Smith");                           Example<Person> example = Example.of(person); List<Person> results = personRepository.findAll(example); 

Note that this requires very recent 2016 versions

    <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> 

see https://github.com/paulvi/com.example.spring.findbyexample

like image 55
Adam Erstelle Avatar answered Sep 30 '22 10:09

Adam Erstelle