提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
在项目中经常会用到多表联合查询,通过创建两个实体类,使用@One或者@Many注解或者通过编写xml文件来实现联合查询。
现我通过直接在dao层添加sql语句来实现多表查询操作
一、创建设备实体类
@Data
@TableName("device")
public class DevEntity {
//设备id
private Long id;
//归属设备id
private Long parentId;
//设备名
private String devName;
//设备编码
private String devCode;
@TableField(exist = false)
private String parentName;
private Long areaId;
@TableField(exist = false)
private String areaName;
//极限温度
private Double tempMax;
private Double tempMin;
//极限湿度
private Double humidityMax;
private Double humidityMin;
//湿温度阈值
private Double temThrVal;
private Double humThrVal;
private Integer label;
//创建时间,用于计算设备使用时间
private Date createTime;
@TableField(exist = false)
private Boolean open;
@TableField(exist = false)
private List<DevEntity> list = new ArrayList<>();
}
area表字段为id和areaName
我要进行的操作是在controller层中直接调用dao层的getDevList获取设备列表,下面是部分代码。
二、实现流程
1.编写Controller层代码
代码如下
import com.wedu.modules.dev.dao.DevDao;
import com.wedu.modules.dev.entity.DevEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
@Autowired
private DevDao devDao;
@GetMapping("/getequip")
public List<DevEntity> list(){
List<DevEntity> DevList = devDao.getDevList();
HashMap<Long, DevEntity> devMap = new HashMap<>(12);
for (DevEntity s : DevList) {
devMap.put(s.getId(), s);
}
for (DevEntity s : DevList) {
DevEntity parent = devMap.get(s.getParentId());
if (Objects.nonNull(parent)) {
s.setParentName(parent.getDevName());
}
}
return DevList;
}
2.Dao层代码
代码如下(示例):
public interface DevDao extends BaseMapper<DevEntity> {
@Select("SELECT device.*, area.area_name as areaName FROM device LEFT JOIN area ON device.area_id = area.id")
List<DevEntity> getDevList();
}
总结
在使用mybatis-plus中,有以下查询方法:
1.根据主键id去查询单个结果 selectById
2.查询多条数据库中的记录 selectList
3.查询多条数据库中的记录—条件查询 selectList(wrapper)
条件构造器QueryWrapper常用方法:
wrapper.eq(“数据库字段名”, “条件值”); //相当于where条件
wrapper.between(“数据库字段名”, “区间一”, “区间二”);//相当于范围内使用的between
wrapper.like(“数据库字段名”, “模糊查询的字符”); //模糊查询like
wrapper.groupBy(“数据库字段名”); //相当于group by分组
wrapper.in(“数据库字段名”, “包括的值,分割”); //相当于in
wrapper.orderByAsc(“数据库字段名”); //升序
wrapper.orderByDesc(“数据库字段名”);//降序
wrapper.ge(“数据库字段名”, “要比较的值”); //大于等于
wrapper.le(“数据库字段名”, “要比较的值”); //小于等于
4.根据主键的id集合进行多条数据的查询 selectBatchIds
5.分页查询 selectPage
我这里所展示的是自定义sql语句查询,希望给大家带来帮助。