springboot+jpa多表查询
背景
关联起来查询三个表的数据
步骤
- 定义接收结果的中间类
- 在 @Query 中编写 HSQL
- 从数据库查询
代码
定义接收结果的中间类
IterationVo.java
/**
* IterationVo
* @description 封装查询到的迭代详细信息
* @author daleyzou
* @date 2019年11月20日 20:09
* @version 3.0.0
*/
public class IterationVo implements Serializable {
private String businessUnitName;
private String businessLineName;
private int id;
private int businessUnitId;
private int businessLineId;
private String iterationName;
private String item;
private String itemCode;
private String version;
private String note;
private String baseBranchInfo;
private Date createTime;
public IterationVo(IterationPo iterationPo, String businessUnitName, String businessLineName) {
this.id = iterationPo.getId();
this.businessLineId = iterationPo.getBusinessLineId();
this.businessUnitId = iterationPo.getBusinessUnitId();
this.version = iterationPo.getVersion();
this.item = iterationPo.getItem();
this.itemCode = iterationPo.getItemCode();
this.baseBranchInfo = iterationPo.getBaseBranchInfo();
this.note = iterationPo.getNote();
this.iterationName = iterationPo.getIterationName();
this.createTime = iterationPo.getCreateTime();
this.businessUnitName = businessUnitName;
this.businessLineName = businessLineName;
}
set方法 ...
get方法 ...
}
IterationPo.java
@Entity
@Table(name = "iteration")
@EntityListeners(AuditingEntityListener.class)
@DynamicInsert
@DynamicUpdate
public class IterationPo {
private int id;
private int businessUnitId;
private int businessLineId;
private String iterationName;
private String item;
private String itemCode;
private String createUserName;
private String updateUserName;
private String version;
private String note;
private Date createTime;
private Date updateTime;
private String baseBranchInfo;
private int publishing;
private boolean published;
private boolean canFullRelease;
}
在 @Query 中编写 HSQL
IterationDao.java
/**
* IterationDao
* @description 迭代数据库操作
* @author daleyzou
* @date 2019年11月08日 10:53
* @version 3.0.0
*/
@Repository
public interface IterationDao extends JpaRepository<IterationPo, Integer> {
// 分页查询
@Query(value = "SELECT new com.daleyzou.middleware.mwgrayscaledubbo.base.vo.IterationVo(iteration, unit.name, line.name) FROM IterationPo iteration, BusinessUnitPo unit, BusinessLinePo line WHERE iteration.businessUnitId=unit.id and iteration.businessLineId=line.id ")
Page<IterationVo> findIterationInfo(Pageable pageable);
// 根据主键查询
@Query(value = "SELECT new com.daleyzou.middleware.mwgrayscaledubbo.base.vo.IterationVo(iteration, unit.name, line.name) FROM IterationPo iteration, BusinessUnitPo unit, BusinessLinePo line WHERE iteration.businessUnitId=unit.id and iteration.businessLineId=line.id and iteration.id=:id")
IterationVo findIterationInfoById(@Param("id") Integer id);
}
从数据库查询
使用 @Autowried 依赖注入后调用即可
分页在 service 层这样调用
public Page<IterationVo> getIterationList(Integer page, Integer size) {
Pageable pageable = new PageRequest(page, size, Sort.Direction.DESC, "createTime");
return iterationDao.findIterationInfo(pageable);
}