I have an application that uses Spring Boot Data jpa . So far i am using a repository like this
public interface StudentRepository extends CrudRepos
It's very complicated to create specifications using JPA Criteria because the API is very verbose and instrusive.
With the Lambda JDK 8, you can create high very typed-queries using simples predicates.
@Test
public void testSimpleSpec() {
String expected =
"select e0.id, e0.name "
+ "from Customer e0 "
+ "where (e0.regionCode = :p0)";
Consumer> regionCode1 =
q -> q.where(i -> i.getRegionCode()).eq(1L);
NativeSQLResult result = new QueryBuilder()
.from(Customer.class)
.whereSpec(regionCode1)
.select(i -> i.getId())
.select(i -> i.getName())
.to(new NativeSQL())
;
String actual = result.sql();
Assert.assertEquals(expected, actual);
Assert.assertEquals(result.params().get("p0"), 1L);
}
You can isolate the conditions and to reuse in others queries, ie, specifications.
https://github.com/naskarlab/fluent-query
https://github.com/naskarlab/fluent-query-eclipselink