This is a simple library to handle generic search using Criteria/Specification API with JPA.
It generates a JPA Specification<T> with all criterias given a request object.
SpecificationService is the entry point of the specification generator. The generated Specification<T>
can be used with repository.findAll.
@Service
class Service {
private final SpecificationService specificationService;
// ...
List<Entity> = repository.findAll(specificationService.generateSpecification(searchRequest));
// ...
} The SpecificationService bean only needs a JdbcTemplate
@Bean
public SpecificationService specificationService(JdbcTemplate jdbcTemplate) {
return new SpecificationService(jdbcTemplate);
}Define the entity with usual JPA annotation
@Entity
@Table(name = "entity")
public class Entity {
@Id
private Integer entityId;
// ...
}This is the object containing all search parameters.
- Use the annotation
@SearchRequestObjectfor the object holding search values. This object typically comes from a HTTP request (request parameters or request body) - Use the annotation
@SearchPathfor each field of the request object to be mapped into a JPA Criteria.
@SearchRequestObject
public record SearchRequest(@SearchPath("path(name) like ?") Integer entityId) {}The @SearchPath annotation hold all information to generate a JPA criteria.
These informations are a chain of operations to test a value with a field using a SQL like or equal.
- Join
- Values
- Simple values
- Operators
- Types
- Json values
There is an optional bean to validate all expressions set with @SearchPath
@Bean
public SpecificationValidationService specificationValidationService(
ResourceLoader resourceLoader) {
return new SpecificationValidationService(resourceLoader) {
@Override
public String[] packagesToScan() {
return new String[] {"package.that.contain.classes.annotated.with.SearchPath"};
}
};
}ParseException
SearchException