Posts

Showing posts from March, 2015

Spring Data Repositories: Query by Specification

Working with Spring and Spring Data repositories I got the need to have flexible queries based on some of the property of an entity class that should be put in OR in the query if they were present. Instead of creating a query for each combination of properties, I used one of the facilities provided by Spring-Data: the query by Specification. Before going into the details some background information. What I am going to show is an example based on the JpaRepository using Hibernate as persistency layer. A full working example can be found here:  query-by-spec The trick is in the use of the Specification interface in combination with a JpaSpecificationExecutor. Let's start... First we define an entity with some properties: @Entity @Table(name = "person") public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "name") private String name; @Column(name = "surname") private Strin