使用entityManager做分页查询

场景 jpa遇到查询条件不固定的情况下,使用原生sql查询可以解决这个问题

例子

接口类

    @ApiOperation("PC端,根据条件查询审批分页数据")
    @GetMapping("/pc/getPageApproval")
    public Result> getPageOfApproval(ApprovalPcQueryVo pcQueryVo) {
        Page approvalsWithPc = approvalService.findApprovalsWithPc(pcQueryVo);
        return ResultUtils.success(new ResultPageVo(approvalsWithPc));
    }

vo类

@Data
@ApiModel(description = "Pc,审批回参")
public class ApprovalPagePcVo {
    @ApiModelProperty("审批uuid")
    private String uuid;
	@ApiModelProperty("客户名")
    private String customerName;

    @ApiModelProperty("赔款金额或退款金额")
    private BigDecimal payAmount;

    @ApiModelProperty("服务名称")
    private String serverName;

    @ApiModelProperty("申请类型,0:转会、1:延期、2:赔偿、3:退项、4:退卡、5:余项调整、6:余额调整")
    private Integer type;
    @ApiModelProperty("申请类型名称")
    private String typeName;

    @ApiModelProperty("申请人(顾问)名称")
    private String applyName;

    @ApiModelProperty("顾问所在门店名")
    private String storeName;

    @ApiModelProperty("品牌名")
    private String supplierName;

    @ApiModelProperty("状态,0:待审核、1:已通过、2:已拒绝、3:异常失败、4:系统处理中")
    private Integer state;

    @ApiModelProperty("状态,0:待审核、1:已通过、2:已拒绝、3:异常失败、4:系统处理中")
    private String stateName;

    @ApiModelProperty("申请时间")
    private String date;

    @ApiModelProperty("更新时间")
    private String updateTime;

    public String getTypeName() {
        return ApprovalTypeEnum.getMeassge(type);
    }
    
    public String getStateName() {
        return ApprovalStateEnum.getMessage(state);
    }
}
  • service类

     public Page findApprovalsWithPc(ApprovalPcQueryVo pcQueryVo) {
         UuidListDto dto = storeClient.getStoreUuids();
         if (dto == null || dto.getUuids() == null || dto.getUuids().size() == 0) {
             throw new BusinessException("没有门店数据权限");
         }
         UserDTO userDTO = ContextUtil.getCurrentUser();
         pcQueryVo.setSupplierCode(userDTO.getSupplierCode());
         List readVos = approvalDao.getApprovalsPageWithPc(pcQueryVo,dto.getUuids());
         Long total = approvalDao.countGetApproval(pcQueryVo,dto.getUuids());
         Page readVoPage = new PageImpl<>(readVos, PageRequest.of(pcQueryVo.getPage().getCurrentPage(), pcQueryVo.getPage().getPageSize()), total);
         return readVoPage;
     }
    

dao层

  • 获取list

    public List getApprovalsPageWithPc(ApprovalPcQueryVo queryVo,List uuids) {
         Query query = entityManager.createNativeQuery(generatorNativeSql(queryVo, false, uuids));
         Map map = generatorParamMap(queryVo);
         map.forEach((k, v) -> {
             query.setParameter(k, v);
         });
         query.setFirstResult(queryVo.getPage().getCurrentPage() * queryVo.getPage().getPageSize());//起始数
         query.setMaxResults(queryVo.getPage().getPageSize());
         query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(ApprovalPagePcVo.class));
         return query.getResultList();
     }
    
  • 工厂类

      private String generatorNativeSql(ApprovalPcQueryVo queryVo, boolean isCount,List uuids) {
          StringBuilder sql = new StringBuilder();
          if (isCount) {
              sql.append("select count(1)");
          } else {
              sql.append("select a.uuid," +
                      " a.apply_name  as applyName," +
                      " a.store_name    as storeName," +
                      " a.supplier_name  as supplierName," +
                      " date_format(a.create_time,'%Y-%m-%d %T')  as date," +
                      " date_format(a.update_time,'%Y-%m-%d %T')  as updateTime," +
                      " a.customer_name   as customerName," +
                      " a.pay_amount  as  payAmount," +
                      " a.server_name  as serverName,"+
                      " a.state," +
                      " a.type");
          }
          sql.append(" from t_approval a where 1=1 ");
    
          StringBuilder sp = new StringBuilder(" and a.store_uuid in ( ");
          int i=0;
          for(String s:uuids){
              if(i==0){
                  sp.append("'"+s+"'");
              }else{
                  sp.append(",'"+s+"'");
              }
              i++;
          }
          sp.append(")");
          sql.append(sp);
    
          if (Objects.nonNull(queryVo)) {
              if (!ObjectUtils.isEmpty(queryVo.getSupplierCode())) {
                  sql.append(" and a.approver_uuid = :approverUuid");
              }
              if (Objects.nonNull(queryVo.getType())) {
                  sql.append(" and a.type= :type");
              }
              if (!StringUtils.isEmpty(queryVo.getApplyName())) {
                  sql.append(" and a.apply_name like :applyName");
              }
              if (Objects.nonNull(queryVo.getState())) {
                  sql.append(" and a.state= :state");
              }
              if (!StringUtils.isEmpty(queryVo.getStart())) {
                  sql.append(" and date_format(a.create_time,'%Y-%m-%d')>= :start");
              }
              if (!StringUtils.isEmpty(queryVo.getEnd())) {
                  sql.append(" and date_format(a.create_time,'%Y-%m-%d')<= :end");
              }
          }
          sql.append(" order by a.create_time desc");
          return sql.toString();
      }
    

工厂类

	 public Page findApprovalsWithPc(ApprovalPcQueryVo pcQueryVo) {
	     UuidListDto dto = storeClient.getStoreUuids();
	     if (dto == null || dto.getUuids() == null || dto.getUuids().size() == 0) {
	         throw new BusinessException("没有门店数据权限");
	     }
	     UserDTO userDTO = ContextUtil.getCurrentUser();
	     pcQueryVo.setSupplierCode(userDTO.getSupplierCode());
	     List readVos = approvalDao.getApprovalsPageWithPc(pcQueryVo,dto.getUuids());
	     Long total = approvalDao.countGetApproval(pcQueryVo,dto.getUuids());
	     Page readVoPage = new PageImpl<>(readVos, PageRequest.of(pcQueryVo.getPage().getCurrentPage(), pcQueryVo.getPage().getPageSize()), total);
	     return readVoPage;
	 }
  • 获取总记录数

    public Long countGetApproval(ApprovalPcQueryVo queryVo,List uuids) {
         Query query = entityManager.createNativeQuery(generatorNativeSql(queryVo, true, uuids));
         Map map = generatorParamMap(queryVo);
         map.forEach((k, v) -> {
             query.setParameter(k, v);
         });
         BigInteger total = (BigInteger) query.getSingleResult();
         return total.longValue();
    }
    

你可能感兴趣的:(#,数据层)