网站建设网站徒手整形百度高搜
文章目录
- 背景
- 方案推荐
- 创建 DTO
- 创建 Mapper
- 创建对应 xml
- Service 代码
背景
假如同 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);
}