MabatisPlus 多表联查
近期使用MabatisPlus时需要进行多表联查,但是在找方法时发现自己引入的包中似乎不能使用LeftJoin方法,于是,便从中取了一个巧,通过自己来二次查询构建出自己想要的数据对象
首先是商品实体类
@Data
public class Goods {
@TableId
private Integer id;
private String title;
private String info;
private String prise;
private String imgurl;
private long loadtime;
private int userId;
@TableField(exist = false)
private User user;
}
使用了注解@Data
就不需要再写get、set方法了
注解@TableId
用于指定数据表所对应的主键属性
注解@TableField(exist = false)
用于声明,这并不是数据表中存在的字段,可以理解为虚拟字段,在进行普通查询时,并不会影响到查询结果
解决方法
@Autowired
private GoodsMapple goodsMapple;
@Autowired
private UserMapple userMapple;
//引入注解依赖注入
@GetMapping("/getgoodsbyid")
//请求方法以及路径
public List<Goods> getgoodsbyid(){
QueryWrapper<Goods> wrapper = new QueryWrapper<>();
//构造查询对象
List<Goods> orderList = goodsMapple.selectList(new QueryWrapper<>());
//先将普通的商品数据查出
for (Goods order : orderList) {
// 进行关联查询,并设置关联对象
User user = userMapple.selectById(order.getUserId());
order.setUser(user);
//通过商品用户id,执行每一个商品用户的信息查询,并将其赋予该集合中
}
return orderList;
}
总而言之,相当于是执行了两次查询流程,第一次是查询普通的商品信息,其中就包含了商品持有者的id属性,第二次,遍历每一个商品,使用持有者id作为条件查询用户表中的信息,作为值赋给商品类中的属性User,这样子每一个商品类中就包含了完整信息