QueryWrapper多表联查分页、IPage分页
解决IPage+ QueryWrapper 多表联查、条件搜素、模糊匹配的分页问题
- 假如我们有一张user表,和一张department表 (关联关系表)
- 要通过department(模糊匹配)到所有的user并且分页
实体类
@ApiModel(description = "用户")
public class User {
@ApiModelProperty(value = "主键")
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "外键")
private Integer departmentId;
}
@ApiModel(description = "部门")
public class User {
@ApiModelProperty(value = "主键")
private Integer id;
@ApiModelProperty(value = "部门名称")
private String departmentName;
controller
@PostMapping("/user")
@ApiOperation("用户条件查询")
public ApiResponse<User> selectUser(@RequestBody Map<String, Object> queryMap) {
try {
return ApiResponse.ofSuccess(UserService.selectUser(queryMap));
} catch (Exception e) {
log.error("查询失败", e);
return ApiResponse.ofError("查询查询失败");
}
}
service
- 注意 返回值为IPage
IPage<User> selectUser(Map<String, Object> queryMap);
Impl
- user 为主表,正常使用QueryWrapper 查询即可
- department 为关联表,字段名必须和xml中对应
@Override
public IPage<TcmcAlarm> eqAllAlarm(Map<String, Object> params) {
// size 每页多少条
long size = Long.parseLong(StringUtils.defaultIfBlank(String.valueOf(params.get("limit")), "10"));
// 当前页
long current = Long.parseLong(StringUtils.defaultIfBlank(String.valueOf(params.get("page")), "1"));
}
// 定义 QueryWrapper
QueryWrapper<TcmcAlarm> q = new QueryWrapper<>();
// 用户名(主表)
Object userName = params.get("userName");
// 部门名称
Object alarmType = params.get("departmentName");
// 用户名模糊查询(常规查询)
if (null != userName && userName.toString().trim().length() > 0) {
q.lambda().like(User::getUserName(), userName);
}
// 联接表
if(null != departmentName && departmentName.toString().trim().length() > 0){
q.eq("dt.department_name", departmentName);
}
IPage<TcmcAlarm> page = baseMapper.selectUserpage(
new Page<>(current, size), q);
return page;
department.department_name
- dt 表名,department_name 表字段
- 重写selectUserpage
常规操作中ServiceImpl
封装了很多方法我们可以直接使用,其中就有分页,但是牵扯到复杂查询时我们尽量选择重写(如下) - Impl
- mapper
重写的mapper
IPage<User> selectUserpage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<User> queryWrapper);
xml
<select id="selectUserpage" resultType="XXX.user">
SELECT
us.id id,
us.username username
dt.department_name departmentName
FROM
user us
LEFT JOIN department dt ON dt .id = us.departmentId
${ew.customSqlSegment}
</select>
${ew.customSqlSegment}
相当于一个占位符,后续当你在mp的条件构造器中加入条件,mp的底层就会根据条件自动的在这个占位符处进行条件的拼接
最终sql
SELECT
us.id id,
us.username username
dt.department_name departmentName
FROM
user us
LEFT JOIN department dt ON dt .id = us.departmentId
where
dt.dt.department_name = "XX"
QueryWrapper条件查询
QueryWrapperLambdaQueryWrapper-(条件查询)
总结
本片文章例子较为简单,只说明用法,谢谢点赞和指正。