In the last tutorial we saw how to use Specifications. In this tutorial we will learn how to combine multiple specifications by using following methods of Specification interface:
static <T> Specification<T> not(Specification<T> spec)
static <T> Specification<T> where(Specification<T> spec)
default Specification<T> and(Specification<T> other)
default Specification<T> or(Specification<T> other)
Example
Entities
@Entity
public class Employee {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Phone> phones;
.............
}
@Entity
public class Phone {
@Id
@GeneratedValue
private long id;
private PhoneType type;
private String number;
.............
}
public enum PhoneType {
Home,
Cell,
Work
}
Creating Combined Specifications
package com.logicbig.example;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.ListJoin;
import javax.persistence.criteria.Predicate;
public class EmployeeSpecs {
public static Specification<Employee> getEmployeesByNameSpec(String name) {
return (root, query, criteriaBuilder) -> {
Predicate equalPredicate = criteriaBuilder.equal(root.get(Employee_.name), name);
return equalPredicate;
};
}
public static Specification<Employee> getEmployeesByPhoneTypeSpec(PhoneType phoneType) {
return (root, query, criteriaBuilder) -> {
ListJoin<Employee, Phone> phoneJoin = root.join(Employee_.phones);
Predicate equalPredicate = criteriaBuilder.equal(phoneJoin.get(Phone_.type), phoneType);
query.distinct(true);
return equalPredicate;
};
}
public static Specification<Employee> getEmployeesByNameOrPhoneTypeSpec(String name,
PhoneType phoneType) {
return Specification.where(getEmployeesByNameSpec(name))
.or(getEmployeesByPhoneTypeSpec(phoneType));
}
public static Specification<Employee> getEmployeesByNameAndPhoneTypeSpec(String name,
PhoneType phoneType) {
return Specification.where(getEmployeesByNameSpec(name))
.and(getEmployeesByPhoneTypeSpec(phoneType));
}
public static Specification<Employee> getEmployeeByNotNameSpec(String name) {
return Specification.not(getEmployeesByNameSpec(name));
}
}
Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long>,
JpaSpecificationExecutor<Employee> {
}
Example Client
@Component
public class ExampleClient {
@Autowired
private EmployeeRepository repo;
public void run() {
List<Employee> persons = createEmployees();
repo.saveAll(persons);
findAllEmployees();
findEmployeesByNameOrPhoneType();
findEmployeesByNameAndPhoneType();
findEmployeesByNotName();
}
private void findEmployeesByNameOrPhoneType() {
System.out.println("-- finding employees with name='Tim' OR PhoneType=Cell --");
List<Employee> list = repo.findAll(
EmployeeSpecs.getEmployeesByNameOrPhoneTypeSpec("Tim", PhoneType.Cell));
list.forEach(System.out::println);
}
private void findEmployeesByNameAndPhoneType() {
System.out.println("-- finding employees with name='Jack' AND PhoneType=Cell --");
List<Employee> list = repo.findAll(
EmployeeSpecs.getEmployeesByNameAndPhoneTypeSpec("Jack", PhoneType.Cell));
list.forEach(System.out::println);
}
private void findEmployeesByNotName() {
System.out.println("-- finding employees with name not 'Mike' --");
List<Employee> list = repo.findAll(
EmployeeSpecs.getEmployeeByNotNameSpec("Mike"));
list.forEach(System.out::println);
}
private void findAllEmployees() {
System.out.println(" -- getting all Employees --");
Iterable<Employee> iterable = repo.findAll();
List<Employee> allEmployees = StreamSupport.stream(iterable.spliterator(), false)
.collect(Collectors.toList());
allEmployees.forEach(System.out::println);
}
private static List<Employee> createEmployees() {
return Arrays.asList(Employee.create("Diana",
Phone.of(PhoneType.Home, "111-111-111"), Phone.of(PhoneType.Work, "222-222-222")),
Employee.create("Mike",
Phone.of(PhoneType.Work, "333-111-111"), Phone.of(PhoneType.Cell, "333-222-222")),
Employee.create("Tim", Phone.of(PhoneType.Work, "444-111-111"), Phone
.of(PhoneType.Home, "444-222-222")),
Employee.create("Jack", Phone.of(PhoneType.Cell, "555-222-222")));
}
}
Main class
public class ExampleMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
ExampleClient exampleClient = context.getBean(ExampleClient.class);
exampleClient.run();
EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
emf.close();
}
} -- getting all Employees -- Employee{id=1, name='Diana', phones=[Phone{id=2, type=Home, number='111-111-111'}, Phone{id=3, type=Work, number='222-222-222'}]} Employee{id=4, name='Mike', phones=[Phone{id=5, type=Work, number='333-111-111'}, Phone{id=6, type=Cell, number='333-222-222'}]} Employee{id=7, name='Tim', phones=[Phone{id=8, type=Work, number='444-111-111'}, Phone{id=9, type=Home, number='444-222-222'}]} Employee{id=10, name='Jack', phones=[Phone{id=11, type=Cell, number='555-222-222'}]} -- finding employees with name='Tim' OR PhoneType=Cell -- Employee{id=7, name='Tim', phones=[Phone{id=8, type=Work, number='444-111-111'}, Phone{id=9, type=Home, number='444-222-222'}]} Employee{id=4, name='Mike', phones=[Phone{id=5, type=Work, number='333-111-111'}, Phone{id=6, type=Cell, number='333-222-222'}]} Employee{id=10, name='Jack', phones=[Phone{id=11, type=Cell, number='555-222-222'}]} -- finding employees with name='Jack' AND PhoneType=Cell -- Employee{id=10, name='Jack', phones=[Phone{id=11, type=Cell, number='555-222-222'}]} -- finding employees with name not 'Mike' -- Employee{id=1, name='Diana', phones=[Phone{id=2, type=Home, number='111-111-111'}, Phone{id=3, type=Work, number='222-222-222'}]} Employee{id=7, name='Tim', phones=[Phone{id=8, type=Work, number='444-111-111'}, Phone{id=9, type=Home, number='444-222-222'}]} Employee{id=10, name='Jack', phones=[Phone{id=11, type=Cell, number='555-222-222'}]}
Example ProjectDependencies and Technologies Used: - spring-data-jpa 2.1.0.RELEASE: Spring Data module for JPA repositories.
Uses org.springframework:spring-context version 5.1.0.RELEASE - hibernate-core 5.3.6.Final: Hibernate's core ORM functionality.
Implements javax.persistence:javax.persistence-api version 2.2 - hibernate-jpamodelgen 5.3.6.Final: Annotation Processor to generate JPA 2 static metamodel classes.
- h2 1.4.197: H2 Database Engine.
- JDK 1.8
- Maven 3.5.4
|
|