CriteriaOperator is a lightweight, zero dependency*, and type-safe wrapper around Java Persistence Criteria API, which simplifies building queries, particularly useful within REST SQL (RSQL) context.
Example of REST query that can be interpreted by the library:
http://localhost:64503/pets?birthdate.gte=2010-01-11&nickname.like=BaWhich results in the following select:
select
p1_0.id,
p1_0.birthdate,
p1_0.name,
p1_0.pet_type_id
from
pet p1_0
where
p1_0.name like ? escape ''
and p1_0.birthdate>=?There are a couple of easy steps to achieve the above:
- Add the dependency
<dependency>
<groupId>md.adrian</groupId>
<artifactId>crop</artifactId>
<version>0.1.3</version>
</dependency>- Define a DTO that contains all fields necessary for filtering. For example, if you want to do filtering on
Stringtype then you chooseStringCriteriaOperatorfrommd.adrian.crop.operatorpackage.
@Getter
@Setter
public class PetSearchCriteria {
private StringCriteriaOperator nickname;
private LocalDateCriteriaOperator birthdate;
}- Create an instance of the service that will parse the query. It requires
EntityManagerin the constructor.
@Bean
CriteriaOperatorService cropService(EntityManager entityManager) {
return new CriteriaOperatorService(entityManager);
}- Finally, invoke the service's
createmethod with the root entity and filter object. The result is a builder that lets you match the entity's meta-model with each field from the DTO. When done, execute the query.
@GetMapping("/pets")
List<PetRecord> search(PetSearchCriteria petSearchCriteria) {
return cropService.create(Pet.class, petSearchCriteria)
.match(PetSearchCriteria::getNickname, Pet_.name)
.match(PetSearchCriteria::getBirthdate, Pet_.birthdate)
.getResultList()
.stream()
.map(petMapper::map)
.toList();
}For full example and to see all the capabilities of the library checkout the crop-test module within this project, which contains integration tests and demonstrations of the library features.
* Zero dependency means that the library does not bring any additional dependencies apart from those required by JPA itself. It uses Spring Framework for testing purposes only, and is not shipped with the library.
Note: The crop-test module is disabled by default to keep the build lightweight. To build it:
- Locally: Use
mvn clean install -Pwith-teststo explicitly enable the test module - In CI/CD: The workflow explicitly activates the profile using
-Pwith-tests
Building with custom version: The project uses CI-friendly versioning. To build with a specific version: mvn clean install -Drevision=1.0.0