springboot+mybatis按条件分页查询多张表

背景

假如同 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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

abcnull

您的打赏是我创作的动力之一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值