Spring boot JPA读取数据库方法

方法1:

 1 StringBuffer sb = new StringBuffer(300);
 2         sb.append("SELECT v.id, v.container_number, v.error_feedback,v.is_handled,v.job_type,v.remark,v.vessel_voyage_number,");
 3         sb.append("e.error_code,e.error_description");
 4         sb.append(" FROM vessel_container_error v");
 5         sb.append(" JOIN error e ON e.error_id = v.error_id");
 6         sb.append(" where v.vessel_voyage_number = '").append(vesselVoyageNumber).append("' and v.container_number = '").append(containerNumber).append("'");
 7         sb.append(" and v.job_type = '").append(jobType).append("' and is_handled = 0");
 8 
 9         List<Object[]> re = this.vesselContainerErrorRespository.listBySQL(sb.toString());
10         List<VesselContainerErrorsBean> list = new ArrayList<>();
11         re.forEach(
12                 objects -> {
13                     VesselContainerErrorsBean errorsBean = new VesselContainerErrorsBean();
14                     errorsBean.setId(objects[0] == null ? 0 : (int) objects[0]);
15                     errorsBean.setContainerNumber(objects[1] == null ? "" : objects[1].toString());
16                     errorsBean.setErrorFeedback(objects[2] == null ? "" : objects[2].toString());
17                     errorsBean.setHandled(objects[3] == null ? false : (Boolean) objects[3]);
18                     errorsBean.setJobType(objects[4] == null ? "" : objects[4].toString());
19                     errorsBean.setRemark(objects[5] == null ? "" : objects[5].toString());
20                     errorsBean.setVesselVoyageNumber(objects[6] == null ? "" : objects[6].toString());
21                     errorsBean.setErrorCode(objects[7] == null ? "" : objects[7].toString());
22                     errorsBean.setErrorDescription(objects[8] == null ? "" : objects[8].toString());
23                     list.add(errorsBean);
24                 }
25         );

优点:

1. 原生Sql , 可以使用数据库自带的方法

2. 适应不定查询条件数量的情况

缺点:

1. 读出来的是 List<Ojbect[]> , 数据转换时要人工对数组下标,判 null

方法2:

 1 StringBuilder countSelectSql = new StringBuilder(300);
 2         countSelectSql.append("select count(*) ");
 3 
 4         StringBuilder selectSql = new StringBuilder(500);
 5         selectSql.append("select new net.pingfang.yard.core.domain.bo.JobPlanAndInsAndEquBO(");
 6         selectSql.append("i.id,i.containerNumber,i.isoCode,i.originalPositionType,i.originalPositionValue,");
 7         selectSql.append("i.targetPositionType,i.targetPositionId,i.targetPositionValue,i.instructionStatusCode,i.planStart,i.actualStart,i.createBy,i.equipmentId,");
 8         selectSql.append("j.jobPlanCode,j.jobTypeCode)");
 9 
10         StringBuilder fromSql = new StringBuilder(250);
11         fromSql.append(" from InstructionEntity i join JobPlanEntity j on i.jobPlanId = j.id");
12 
13         StringBuilder whereSql = new StringBuilder();
14         whereSql.append(" where j.jobPlanCode = :jobPlanCode");
15 
16         Map<String, Object> params = new HashMap<>();
17         params.put("jobPlanCode", jobPlanCode);
18 
19         if (!StringUtils.isEmpty(containerNumber)) {
20             whereSql.append(" and i.containerNumber = :containerNumber");
21             params.put("containerNumber", containerNumber);
22         }
23         if (!StringUtils.isEmpty(equipmentCode)) {
24             fromSql.append(" join EquipmentEntity e on i.equipmentId = e.id");
25             whereSql.append(" and e.equipmentCode = :equipmentCode");
26             params.put("equipmentCode", equipmentCode);
27         }
28         if (null != instructionStatusCode && !instructionStatusCode.isEmpty()) {
29             whereSql.append(" and i.instructionStatusCode in :instructionStatusCode");
30             params.put("instructionStatusCode", instructionStatusCode);
31         }
32 
33         int total = this.getTotalByHql(countSelectSql.append(fromSql).append(whereSql).toString(), params);
34         PageBean page = new PageBean(total, pageNumber, pageSize);
35         if (total > 0) {
36             List<JobPlanAndInsAndEquBO> result = this.searchByHql(selectSql.append(fromSql).append(whereSql).toString(), JobPlanAndInsAndEquBO.class, params, pageNumber, pageSize);
37             page.setContent(result.stream().map(this::toJobPlanAndInsAndEquDTO).collect(Collectors.toList()));
38         }

优点:

1. Hql, 没有使用 JPA  , 而是使用了 EntityManager

2. 适应不定查询条件数量的情况

3. 解决了方法1的缺点

缺点:

1. 解决了方法1 中 List<Ojbect[]> 的问题,但也产生了一个要注意的地方,select 后面使用了一个 POJO 把从数据库读出来的属性包起来了

  1.1 POJO里面构造函数的参数的顺序与从数据库读出来的属性的顺序要一一对应

  1.2 select 后面的 POJO 要写全路径

方法3:

1 @Query(value = "select i.targetPositionId as wagonId,sum(c.containerSize) as containerSize" +
2             " from InstructionEntity i join ContainerDetailEntity c on i.containerId = c.id" +
3             " where i.instructionStatusCode <> 'done' and i.targetPositionType = 'train' and i.targetPositionId = ?1" +
4             " group by i.targetPositionId")
5     ContainersInWagonInterface findInstructionByWagonId(int wagonId);
1 public interface ContainersInWagonInterface extends ContainersInterface {
2 
3     Integer getWagonId();
4     String getWagonNumber();
5 }

优点:

1. 这种方法返回是个接口,也可以是接口的列表,属性的顺序不要求与接口中的属性顺序一致

缺点:

1. hql 语句 select 后面的属性必须使用别名且与接口里的方法名一致

2. hql 读出来的属性可能为 null , 使用时要 判 null

3. 适用于查询条件数量固定的情况 , 条件数量不固定推荐使用 方法2

方法1是我以前常用的方法,方法2和方法3 是最近用到的,个人感觉比方法1好多,这里作个记录。当然 JPA 自带其它方法可以解决 sql 级联查询的问题,如标签 @onetomany 、@manytomany 。若不需要级联查询,用 JPA提供的方法就足够了。

猜你喜欢

转载自www.cnblogs.com/leohe/p/10350072.html