一、序言
衆所周知,MybatisPlus在處理單表DAO操作時非常的友善。在處理多表連接配接連接配接查詢也有優雅的解決方案。今天分享MybatisPlus基于Lambda表達式優雅實作聚合分組查詢。
由于視訊的互動性更強,保留更多的細節,看視訊的朋友,傳送門在這裡。
下面的内容是部落格文字版。
二、代碼實作
1、使用者實體類
@TableName(value = "tb_user")
public class User {
private static final long serialVersionUID = 1L;
private Integer age;
private Long deptId;
@TableId(type = IdType.AUTO)
private Long userId;
private String userName;
public User(User user) {
if (Objects.nonNull(user)) {
this.age = user.age;
this.deptId = user.deptId;
this.userId = user.userId;
this.userName = user.userName;
}
}
}
2、使用者聚合類
本類屬于核心代碼
@TableName(value = "tb_user")
public class UserAggr {
private Long deptId;
/**
* 新增的一列資料 用于存儲count字段
* 注解非常關鍵
*/
@TableField(value = "count(*)", insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER)
private Long count;
public UserAggr(UserAggr user) {
if (Objects.nonNull(user)) {
this.deptId = user.deptId;
this.count = user.count;
}
}
}
3、使用者聚合類VO
public class UserAggrVo extends UserAggr {
private String deptName;
/**
* 很重要構造器
*
* @param user
*/
public UserAggrVo(UserAggr user) {
super(user);
}
}
4、服務層調用
public List<UserAggrVo> selectList3() {
LambdaQueryWrapper<UserAggr> wrapper = Wrappers.lambdaQuery(UserAggr.class)
.select(UserAggr::getDeptId, UserAggr::getCount)
.groupBy(UserAggr::getDeptId);
List<UserAggr> userAggrList = userAggrMapper.selectList(wrapper);
List<UserAggrVo> userAggrVoList = EntityUtils.toList(userAggrList, UserAggrVo::new);
// 給deptName完成屬性指派
Set<Long> deptIds = EntityUtils.toSet(userAggrVoList, UserAggrVo::getDeptId);
if (deptIds.size() > 0) {
List<Dept> deptList = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class)
.in(Dept::getDeptId, deptIds));
Map<Long, String> map = EntityUtils.toMap(deptList, Dept::getDeptId, Dept::getDeptName);
for (UserAggrVo userAggrVo : userAggrVoList) {
userAggrVo.setDeptName(map.get(userAggrVo.getDeptId()));
}
}
return userAggrVoList;
}
5、效果展示
{
"code": 200,
"msg": "操作成功",
"data": [
{
"deptId": "10",
"count": "1",
"deptName": "Java"
},
{
"deptId": "11",
"count": "2",
"deptName": "Mysql"
},
{
"deptId": "12",
"count": "3",
"deptName": "Tomcat"
}
]
}