多表的分页查询

来源:4-2 分页查询

Keily

2021-11-20 20:35

我这里有两张表,user-用户表(id,name,manager_id,dept_id),department-部门表,我需要查询的数据是,人员名称,人员所在部门名称这样的信息;

实体: user,department,userVo(user,和deparment对象)

mapper:

public IPage<UserVo> selectUserVoByPage(Page<UserVo> page, @Param(Constants.WRAPPER)Wrapper<UserVo> wrapper);

mapper xml:

<select id="selectUserVoByPage" resultType="UserVo">
    select a.id as "user.id",
           a.name as "user.name",
           b.id as "department.id",
           b.name as "department.name"
    from user a
             left join department b on b.id = a.dept_id
     ${ew.customSqlSegment}
</select>

分页查询:

Page<UserVo> page1 = new Page<UserVo>(1, 5);
QueryWrapper<UserVo> userVoWrapper = Wrappers.<UserVo>query();
userVoWrapper.like("a.name", "王");
userVoWrapper.gt("a.age", 20);
userVoWrapper.like("b.name", "信息部");
IPage<UserVo> userVoIPage = userMapper.selectUserVoByPage(page1, userVoWrapper);
List<UserVo> userVoList = userVoIPage.getRecords();
userVoList.forEach(System.out::println);

返回结果:

Preparing: SELECT COUNT(1) FROM user a LEFT JOIN department b ON b.id = a.dept_id WHERE a.name LIKE ? AND a.age > ? AND b.name LIKE ? 

Parameters: %王%(String), 20(Integer), %信息部%(String)

Preparing: select a.id as "user.id", a.name as "user.name", b.id as "department.id", b.name as "department.name" from user a left join department b on b.id = a.dept_id WHERE a.name LIKE ? AND a.age > ? AND b.name LIKE ? LIMIT ?,? 

Parameters: %王%(String), 20(Integer), %信息部%(String), 0(Long), 5(Long)

UserVo(user=User(id=2, name=王天风, age=null, email=null, managerId=null, createTime=null, deptId=null, remark=null, remark3=null), department=Department(id=2, name=信息部-开发一部))


这样可以实现多表关联的分页查询,再优化下mapper里边的select查询列,和外链接多表,会更好点。

写回答 关注

1回答

  • 慕梦前来
    2022-04-20 21:46:56

    这查询用*是真的不好,不要学

MyBatis-Plus入门

MyBatis-Plus框架入门必学课程!

56140 学习 · 381 问题

查看课程

相似问题