springboot+mybatis按条件分页查询多张表
- 软件开发
- 2025-09-04 00:06:01

文章目录 背景方案推荐创建 DTO创建 Mapper创建对应 xmlService 代码 背景
假如同 mysql 数据源下有如下几张表:
用户基础信息表用户地址表用户学历信息表我希望做分页查询用户数据,用户数据为各个表内信息的汇总,并且这个分页查询会根据各种条件来查询
那么通常该如何做呢?
方案推荐一般情况下通用推荐(下面主讲): 使用 join 进行多表连接查询,使用 pagehelper 分页插件,通过 MyBatis 的 <resultMap> 和 JOIN 语句实现多表关联,使用 MyBatis 动态 SQL 标签(如 )处理条件组合
其他方案:
方式一:将高频查询字段冗余到主表,形成宽表,此方案牺牲空间换取性能,以后直接分页查询一张表即可方式二:分步骤来查询,在代码层面进行数据组装 创建 DTO创建 dto 做查询数据接收的对象
public class UserQueryDTO { private String name; // 用户姓名(模糊查询) private String province; // 省份条件 private String degree; // 学历条件 } 创建 Mapper创建一个 mapper 接口 selectUserWithConditions
创建对应 xml <!-- UserMapper.xml --> <select id="selectUserWithConditions" resultMap="UserResultMap"> SELECT u.id, u.name, a.province, e.degree FROM user u LEFT JOIN address a ON u.id = a.user_id LEFT JOIN education e ON u.id = e.user_id <where> <if test="name != null and name != ''"> u.name LIKE CONCAT('%', #{name}, '%') </if> <if test="province != null and province != ''"> AND a.province = #{province} </if> <if test="degree != null and degree != ''"> AND e.degree = #{degree} </if> </where> </select> <resultMap id="UserResultMap" type="UserVO"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="province" column="province"/> <result property="degree" column="degree"/> </resultMap> Service 代码 // 使用PageHelper(需在pom.xml 添加依赖) public PageInfo<UserVO> queryUsers(UserQueryDTO dto) { PageHelper.startPage(dto.getPageNum(), dto.getPageSize()); List<UserVO> list = userMapper.selectUserWithConditions(dto); return new PageInfo<>(list); }springboot+mybatis按条件分页查询多张表由讯客互联软件开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“springboot+mybatis按条件分页查询多张表”