Spring Data JPA How to Query and Page Using QueryDsl

  • 2021-12-13 07:52:08
  • OfStack

Directory Spring Data JPA uses QueryDsl query and paging uses QueryDSL

Spring Data JPA Queries and Pages Using QueryDsl


 QProblemPoint qProblemPoint = QProblemPoint.problemPoint;
        Map<String,String> map = getWhere(param);
 
        JPAQuery<ProblemPoint> query = jpaQueryFactory
                .selectFrom(qProblemPoint)
                .where(
                        qProblemPoint.problemClassify.like(map.get("problemClassify")),// Problem classification 
                        qProblemPoint.problemLevel.like(map.get("problemLevel")),// Problem level 
                        qProblemPoint.securityRiskEvent.like(map.get("securityRiskEvent")),// Risk event 
                        qProblemPoint.riskItems.like(map.get("riskItems"))// Security risk item 
                );
 
        List<ProblemPoint> list = query
                .offset(param.getStart())
                .limit(param.getLength()).fetch();
        long count = query.fetchCount();
QProblemPoint Is a compiled entity query Collections queried based on criteria list Paging operation according to the information from the foreground .fetch() Equivalent to. get () to see the return type.

Use QueryDSL

Complement springDataJpa, carry out complex dynamic sql statement, carry out sql query, and realize related paging and other functions


@Test
public void testComplexSelect() {
    QQyOnlineCall onlineCall = QQyOnlineCall.qyOnlineCall;
    QClientList clientList = QClientList.clientList;
    // page You must start from 1 Begin 
    PageRequest request = PageRequest.of(0, 10);
    //  Building complex query statements 
    List<Tuple> result = mFactory.select(onlineCall.id, onlineCall.cUsesign, onlineCall.cYgscode, clientList.cClientname, clientList.cPhone1)
            .from(onlineCall)
            .leftJoin(clientList)
            .on(onlineCall.cClientid.eq(clientList.id))
            .where(onlineCall.cCom.eq("C0003"))
            .limit(request.getPageSize()) //  Quantity of queries per page 
            .offset(request.getPageSize() * request.getPageNumber()) //  Offset 
            .fetch();
    //  Get results 
    for (Tuple tuple : result) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", tuple.get(onlineCall.id));
        map.put("useSign", tuple.get(onlineCall.cUsesign));
        map.put("ygsCode", tuple.get(onlineCall.cYgscode));
        map.put("clientName", tuple.get(clientList.cClientname));
        map.put("phone", tuple.get(clientList.cPhone1));
        System.out.println(JsonUtils.toJson(map));
    }
}

Related articles: