眾所周知,MybatisPlus在處理單表DAO操作時(shí)非常的方便。在處理多表連接連接查詢也有優(yōu)雅的解決方案。今天分享MybatisPlus基于Lambda表達(dá)式優(yōu)雅實(shí)現(xiàn)聚合分組查詢。
創(chuàng)新互聯(lián)建站專業(yè)IDC數(shù)據(jù)服務(wù)器托管提供商,專業(yè)提供成都服務(wù)器托管,服務(wù)器租用,資陽托管服務(wù)器,資陽托管服務(wù)器,成都多線服務(wù)器托管等服務(wù)器托管服務(wù)。
由于視頻的交互性更強(qiáng),保留更多的細(xì)節(jié),看視頻的朋友,傳送門在這里。
下面的內(nèi)容是博客文字版。
@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;
}
}
}
本類屬于核心代碼
@TableName(value = "tb_user")
public class UserAggr {
private Long deptId;
/**
* 新增的一列數(shù)據(jù) 用于存儲count字段
* 注解非常關(guān)鍵
*/
@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;
}
}
}
本類屬于核心代碼
public class UserAggrVo extends UserAggr {
private String deptName;
/**
* 很重要構(gòu)造器
*
* @param user
*/
public UserAggrVo(UserAggr user) {
super(user);
}
}
服務(wù)層完成調(diào)用
public List selectList3() {
LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserAggr.class)
.select(UserAggr::getDeptId, UserAggr::getCount)
.groupBy(UserAggr::getDeptId);
List userAggrList = userAggrMapper.selectList(wrapper);
List userAggrVoList = EntityUtils.toList(userAggrList, UserAggrVo::new);
// 給deptName完成屬性賦值
Set deptIds = EntityUtils.toSet(userAggrVoList, UserAggrVo::getDeptId);
if (deptIds.size() > 0) {
List deptList = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class)
.in(Dept::getDeptId, deptIds));
Map map = EntityUtils.toMap(deptList, Dept::getDeptId, Dept::getDeptName);
for (UserAggrVo userAggrVo : userAggrVoList) {
userAggrVo.setDeptName(map.get(userAggrVo.getDeptId()));
}
}
return userAggrVoList;
}
{
"code": 200,
"msg": "操作成功",
"data": [
{
"deptId": "10",
"count": "1",
"deptName": "Java"
},
{
"deptId": "11",
"count": "2",
"deptName": "Mysql"
},
{
"deptId": "12",
"count": "3",
"deptName": "Tomcat"
}
]
}
本方案很好的實(shí)現(xiàn)了MybatisPlus基于Lambda表達(dá)式實(shí)現(xiàn)聚合操作,代碼在形式上與單表保持統(tǒng)一,代碼優(yōu)雅。各位看官朋友點(diǎn)贊支持一波。