JPA Specification
Last updated
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.*;
public class EmployeeSpecification implements Specification<Employee> {
private String name;
public EmployeeSpecification(String name) {
this.name = name;
}
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
if (name == null || name.isEmpty()) {
return criteriaBuilder.conjunction(); // No filter if name is null or empty
}
return criteriaBuilder.like(root.get("name"), "%" + name + "%");
}
}package com.example.demo.repository;
import com.example.demo.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface EmployeeRepository extends JpaRepository<Employee, Long>, JpaSpecificationExecutor<Employee> {
}@Autowired
private EmployeeRepository employeeRepository;
public List<Employee> searchEmployees(String name) {
EmployeeSpecification spec = new EmployeeSpecification(name);
return employeeRepository.findAll(spec);
}public class EmployeeSpecifications {
public static Specification<Employee> hasName(String name) {
return (root, query, builder) -> {
if (name != null) {
return builder.like(root.get("name"), "%" + name + "%");
}
return builder.conjunction();
};
}
public static Specification<Employee> hasDepartment(String department) {
return (root, query, builder) -> {
if (department != null) {
return builder.equal(root.get("department"), department);
}
return builder.conjunction();
};
}
public static Specification<Employee> hasSalaryGreaterThan(Double salary) {
return (root, query, builder) -> {
if (salary != null) {
return builder.greaterThan(root.get("salary"), salary);
}
return builder.conjunction();
};
}
}Specification<Employee> spec = Specification.where(EmployeeSpecifications.hasName("John"))
.and(EmployeeSpecifications.hasDepartment("Engineering"))
.and(EmployeeSpecifications.hasSalaryGreaterThan(50000.0));
List<Employee> employees = employeeRepository.findAll(spec);public Page<Employee> searchEmployeesWithPagination(String name, String department, Double salary, Pageable pageable) {
Specification<Employee> spec = Specification.where(EmployeeSpecifications.hasName(name))
.and(EmployeeSpecifications.hasDepartment(department))
.and(EmployeeSpecifications.hasSalaryGreaterThan(salary));
return employeeRepository.findAll(spec, pageable);
}public Page<Employee> searchEmployeesWithPaginationAndSorting(String name, String department, Double salary, Pageable pageable) {
Specification<Employee> spec = Specification.where(EmployeeSpecifications.hasName(name))
.and(EmployeeSpecifications.hasDepartment(department))
.and(EmployeeSpecifications.hasSalaryGreaterThan(salary));
return employeeRepository.findAll(spec, pageable);
}