JPA uncertain terms Beginners paging query share

  

  Beginner JPA, to meet the demand paging query: uncertain terms, fuzzy, sort requirements, if there is no demand uncertain terms, it is easy to get: direct findByClassNameLikeAndParentIdAndHide (), passing paging parameters Pageable can handle, but preceded by the indefinite term to fend for themselves manually write sql, running around in circles, you check online the great God of the article, by finishing practice, come to the following two implementations. Controller layer I just wrote validate the arguments, Model layer does not need to write any code, service layer code is as follows:

 

    / * * 
     * Paging query system classification list (method) 
     * 
     * @param className 
     * @param the parentId 
     * @param hide 
     * @param pageNum 
     * @param pageSize 
     * @return 
     * / 
    the @Transactional 
    public about ResultMaps is getList (className String, Integer the parentId , Integer hide, int pageNum, int the pageSize) {
         // return the result 
        about ResultMaps is The resultMap = new new about ResultMaps is (); 

        the StringBuilder JPQL = new new the StringBuilder ( " from SysClass S = WHERE. 1. 1 " ); 
        List<Object> = args new new the ArrayList <> (); // set of parameters 

        int I = 0 ; // Parameter position mark
         // Fuzzy queries 
        IF (className =! Null ) {
 //             jpqlBuilder.append ( "like and s.className % "+ className +"% ");   // presence sql injection risk 
            jpql.append ( " and s.className like CONCAT ( '%' ,? " ) .append (I) .append ( " , '%') " ); 
            args.add (className); 
            I ++ ; 
        } 
        // specified query 
        if(! the parentId = null ) { 
            (jpql.append " ? = and s.parentId " ) .append (I) .append ( "  " ); 
            args.add (the parentId); 
            I ++ ; 
        } 
        // Controller LAYER hide parameters are verified to ensure that an integer from 0 to 2, the database only stores 0,1, all query parameters for the 2 
        IF (hide! = 2 ) { 
            jpql.append ( " and s.hide =? " ) .append (I) .append ( "  " ); 
            args.add (hide); 
        } 
        // splicing Sort 
        String = orderJpql "s.sort by desc Order, s.classId " ; 

        // list of queries 
        Query Query = em.createQuery (jpql.toString () + orderJpql);
         // add parameters 
        for ( int J = 0 ; J <args.size () ; J ++ ) { 
            query.setParameter (J, args. GET (J)); 
        } 
        // Add paging information 
        query.setFirstResult ((pageNum - . 1 ) * the pageSize); 
        query.setMaxResults (the pageSize); 

        List <SysClass> = sysClassList query.getResultList ();
         // result of treatment, the need to demonstrate the front end of field returns
        List <the JSONObject> = resultList new new the ArrayList <> ();
         for (SysClass sysClass: sysClassList) {
             // custom tools, the need to return the field object returns json form 
            resultList.add (Util.getCustomInfo (sysClass)) ; 
        } 
        resultMap.put ( " Data " , resultList); 

        // query total number 
        String countJpql = " SELECT COUNT (s.classId) " ; 
        query countQuery = em.createQuery (countJpql + jpql.toString ());
         // Add parameters 
        for ( int J = 0; J <args.size (); J ++ ) { 
            countQuery.setParameter (J, args. GET (J)); 
        } 
        List <Object> = the CountResult countQuery.getResultList (); 

        // paging information processing 
        int Total = Integer.valueOf (the CountResult. GET ( 0 ) .toString ());
         int TotalPage = Total / the pageSize;
         IF (the pageSize% Total =! 0 ) { 
            TotalPage ++ ; 
        } 

        // query result set results filled 
        resultMap.put ( " pageNum "  , pageNum);
        resultMap.put ("pageSize", pageSize);
        resultMap.put("total",total);
        resultMap.put("totalPage", totalPage);

        return resultMap;
    }

 

The following is the second method:

   /**
     * 分页查询系统分类列表(方法二)
     *
     * @param className
     * @param parentId
     * @param hide
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Transactional
    public ResultMap getList(String className, Integer parentId, Integer hide, int pageNum, int pageSize) {
        //返回结果
        ResultMap resultMap = new ResultMap();

        CriteriaBuilder cb = em.getCriteriaBuilder();  //获取CriteriaBuilder实体类
        CriteriaQuery<Tuple> criteriaQuery = cb.createTupleQuery();//列表查询
        CriteriaQuery<Tuple> criteriaQueryCount = cb.createTupleQuery();//统计查询
        Root<SysClass> root = criteriaQuery.from(SysClass.class);   //列表查询的实体对象
        Root<SysClass> rootCount = criteriaQueryCount.from(SysClass.class);   //统计查询的实体对象

        //加载查询的列
        criteriaQuery.multiselect(
                root.get("classId").alias("classId"),
                root.get("className").alias("className"),
                root.get("icon").alias("icon"),
                root.get("parentId").alias("parentId")
        );

        //加载查询统计的内容
        criteriaQueryCount.multiselect(
                cb.count(rootCount.get("classId")).alias("total")  //统计查询总条数,作为页面信息返回
        );

        //条件集合
        List<Predicate> predicates = new ArrayList<>();
        //设定查询条件
        if (className != null) { //模糊搜索
            Path<String> classNamePath = root.get("className");
            predicates.add(cb.like(classNamePath.as(String.class), "%" + className + "%"));
        }
        if (parentId != null) {  //匹配搜索
            Path<Integer> parentIdPath = root.get("parentId");
            predicates.add(cb.equal(parentIdPath.as(Integer.class), parentId));
        }
        if (hide != 2) {   //0.查询隐藏内容 1.查询显示隐藏内容 2.查询全部内容(不加查询条件)
            Path<Integer> hidePath = root.get("hide");
            predicates.add(cb.equal(hidePath.as(Integer.class), hide));
        }

        //加载查询条件
        criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
        criteriaQueryCount.where(predicates.toArray(new Predicate[predicates.size()]));

        //加载排序条件
        Path<Integer> sortPath = root.get("sort");
        Path<Integer> classIdPath = root.get("classId");
        criteriaQuery.orderBy(cb.desc(sortPath.as(Integer.class)),cb.asc(classIdPath.as(Integer.class)));

        //获取查询工具类实体
        TypedQuery query = em.createQuery(criteriaQuery);
//        int totalRows = query.getResultList().size();  //不建议使用该方式,效率差,使用统计查询
        //加入分页信息
        query.setFirstResult((pageNum - 1) * pageSize);
        query.setMaxResults(pageSize);
        List<Tuple> list = query.getResultList();//获取查询结果

        //查询结果解析
        List<Map<String, Object>> dataList = new ArrayList<>(); //解析后的查询结果
        if (list != null && !list.isEmpty()) {

            for (Tuple tu : list) {
                Map<String, Object> itemmap = new HashMap<>();
                for (TupleElement element : tu.getElements()) {
                    itemmap.put(element.getAlias(), tu.get(element.getAlias()));

                }
                dataList.add(itemmap);
            }
        }

        //将查询结果填入结果集中
        resultMap.put("data", dataList);
        resultMap.put("pageNum", pageNum + 1);
        resultMap.put("pageSize", pageSize);
        resultMap.put("totalPage", dataList.size());

        //将统计结果加入结果map中
        TypedQuery queryCount = em.createQuery(criteriaQueryCount);
        List<Tuple> listcount = queryCount.getResultList();
        if (listcount != null && !listcount.isEmpty()) {
            Tuple tu = listcount.get(0);
            for (TupleElement element : tu.getElements()) {
                //将统计查询结果填入结果集中
                resultMap.put(element.getAlias(), tu.get(element.getAlias()));
            }
        }

        return resultMap;
    }

 

个人对比意见:

  1.方法一代码量较少,但是需要自己拼接jpql,易出错,如果对于自己jpql语法很有信心,推荐使用(毕竟我是个懒人);

  2.方法二支持查询指定项,而方法一将对象的全部信息都查了出来,后期自己做了处理后返回给前端。

 

参考文章: 《JPA Criteria Query 的 变态例子》光影路西法,网址:    https://www.jianshu.com/p/69fa02602904

ps:本人第一次发布博文,十分粗糙,望大家多多包涵,取之精华,弃之糟粕。特别鸣谢好友鹏飞关于JPA的指点。

Guess you like

Origin www.cnblogs.com/aloneMoonlit/p/10953814.html