jhipster(springboot+datatable+jpa)后台分页,总结

                  最近用datatable做了一个后台分页,但是后台实体原本没写DTO。就碰到的问题做了一下总结

     一、datatable使用get方式传数据到后台,这是正常的后台分页,不涉及过滤查询和前端传递的排序字段,后面会细讲

     后台使用


@GetMapping("/jobs")
@ResponseBody
public ResponseEntity<List<AuditJob>> getAllTestPages(@ApiParam Pageable pageable) {
log.debug("REST request to get a page of TestPages");
Page<AuditJob> page = auditJobRepository.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/test-pages");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}

二、使用DTO

sql语句:

这里需要注意的是,

1、这里用到了DTO,自己建了一个实体类的DTO,只查询出自己需要的字段,但是字段名必须和Dto的构造参数字段操持一致

2、自定义的查询方法,要加上@Modifing

3、这里使用的对象查询,所以sql语句中要和实体的属性名对应,如果要写原生sql语句,就要写在括号里面加 , nativeQuery = true 

4、Dto类要有getter和setter、构造方法

5、自定义的查询方法不能用自带的Pageable参数,如果要分页需要自己写分页语句。使用框架自带的分页查询泛型必须是数据库存在的实体

   @Transactional
    @Query(value = "select new com.famessoft.oplus.cac.domain.AuditJobDto(id,templateName,createdBy,createdAt,endedAt,auditParams,jobStatus) " +
        "from AuditJob order by ?3 ?4 limit ?1,?2")
    @Modifying
    List<AuditJobDto> findAuditDtoByPage(String start,String end,String orderCol,String order);//这里的end是start+length

这里使用了DTO,要写包名,不然会不认识

注意,泛型那里是返回没有DTO的实体,这样子自己就回映射(注意字段名一定要对应)

这里不是自定义的方法,所以不用写@modifing,这是根据jpa的标准语法来写的

@Query(value = "select new com.famessoft.oplus.cac.domain.AuditJobDto(job.id,job.templateName,job.createdBy,job.createdAt,job.endedAt,job.auditParams,job.jobStatus) " +
        "from AuditJob job ")
    Page<AuditJob> findAuditJobByPage(Pageable pageable);

   

带分页的查询和过滤

@PostMapping("/jobs/page")
    @ResponseBody
    public DataTables getAllTestPages(@RequestParam(value = "start", defaultValue = "0") Integer start,
                                      @RequestParam(value = "length", defaultValue = "10") Integer length,
                                      HttpServletRequest request) {

        String search = request.getParameter("search[value]");
        //针对一个字段排序的
        String orderColumn = request.getParameter("order[0][column]");
        String order = request.getParameter("order[0][dir]");

        //给出默认排序的字段
        String sortCol = null;
        Sort sort = null;

        //获取排序字段
        if (orderColumn != null && orderColumn != "") {
            //获取datatable排序列(从0开始)
            int orderCol = Integer.valueOf(orderColumn);
            sortCol = request.getParameter("columns[" + orderCol + "][data]");

            if (order != null) {
                if (order.toUpperCase().equals(Sort.Direction.DESC)) {
                    sort = new Sort(Sort.Direction.DESC, sortCol);
                } else if (order.toUpperCase().equals(Sort.Direction.ASC)) {
                    sort = new Sort(Sort.Direction.ASC, sortCol);
                }
            }
        }

        DataTables dataTables = new DataTables();
        Pageable pageable = new PageRequest(start / length, length, sort);

        Page<AuditJob> page = auditJobRepository.findAuditJobByPage(pageable);

        if (search == null || search.equals("")) {

            dataTables.setData(page.getContent());
            dataTables.setRecordsTotal(page.getTotalElements());
            dataTables.setRecordsFiltered(page.getTotalElements());
            return dataTables;
        } else {
            //过滤查询
            search = "%" + search + "%";
            List<AuditJobDto> list = auditJobRepository.findAuditDtoLikeByPage(search);
            Page<AuditJob> pageBySearch = auditJobRepository.findAuditJobLikeByPage(search,pageable);
            dataTables.setData(pageBySearch.getContent());
            dataTables.setRecordsTotal(page.getTotalElements());//这是数据总的条数
            dataTables.setRecordsFiltered(pageBySearch.getTotalElements());//过滤查询之后的总数
            return dataTables;
        }
    }

上面那样写其实有点傻,因为碰到了很多问题,因为datatable会吧对象的每个值拆分成每个键值对来传(现在不能回显了),不过类似于

obj={a:1,b:2}传到后台不是obj=>{a:1,b:2}

变成了obj[a]=1

   obj[b]=2

这样的值,而且如果使用get方式传递的话中括号还会被转义,根本取不到值,因为key被转义了,所以我换成了post方式传递,取值的方法很笨,但是我还没查到

java针对datatable标准的接收方法,好的一点是,datatable传值的方式是不会变的,所以这样取datatable的值也不会出错,只是代码看起来不是很舒服而已

sql查询语句

这里写了对多字段的模糊查询,所以写了contat函数,但是这个函数针对模糊查询字段等于null的话,这条数据就不会被查询出来,所以需要用ifnull,

还有个小问题,写了IFNULL函数之后,编译会报错,但是不用管它,这个会正常运行的

https://blog.csdn.net/yaoyao9565/article/details/51305854

@Query(value = "select new com.famessoft.oplus.cac.domain.AuditJobDto(job.id,job.templateName,job.createdBy,job.createdAt,job.endedAt,job.auditParams,job.jobStatus) " +
        "from AuditJob job where concat(IFNULL(templateName,'') ,IFNULL(createdBy,''),IFNULL(createdAt,''),IFNULL(endedAt,''),IFNULL(auditParams,''),IFNULL(jobStatus,'')) like ?1 ")
    Page<AuditJob> findAuditJobLikeByPage(String search,Pageable pageable);

 注:

我如果重写findAll()或者自定义查询然后只取部分的属性,会导致我调用findOne的时候也会只取那些属性。但是后面好像又好了,有点莫名其妙

  

原文地址:https://www.cnblogs.com/zml-java/p/9238155.html