How to use Criteria Queries in Spring Boot Data Jpa Application

前端 未结 6 543
死守一世寂寞
死守一世寂寞 2020-12-04 23:10

I have an application that uses Spring Boot Data jpa . So far i am using a repository like this

public interface StudentRepository extends CrudRepos         


        
6条回答
  •  一个人的身影
    2020-12-04 23:34

    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

提交回复
热议问题