java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot mybatis 条件多表分页查询

springboot+mybatis按条件分页查询多张表的项目实践

作者:abcnull

针对MySQL中多表分页查询需求,推荐使用JOIN进行多表关联,结合PageHelper分页插件,通过MySQL resultMap和JOIN语句实现高效查询,感兴趣的可以了解一下

背景

假如同 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 条件多表分页查询 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

阅读全文