欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

PageHelper插件实现一对多查询时的分页问题

时间:2021-01-28 10:22:48|栏目:JAVA代码|点击:

项目中经常会使用到一对多的查询场景,但是PageHelper对这种嵌套查询的支持不够,如果是一对多的列表查询,返回的分页结果是不对的

参考Github上的说明:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/Important.md

对于一对多的列表查询,有两种方式解决

1、在代码中处理。单独修改分页查询的resultMap,删除collection标签,然后在代码中遍历结果,查询子集

2、使用mybatis提供的方法解决,具体如下

定义两个resultMap,一个给分页查询使用,一个给其余查询使用

<resultMap id="BaseMap" type="com.xx.oo.Activity">
  <id column="id" property="id" jdbcType="INTEGER"/>
    ....
</resultMap>

<resultMap id="ResultMap" type="com.xx.oo.Activity" extends="BaseMap">
  <collection property="templates" ofType="com.xx.oo.Template">
    <id column="pt_id" property="id" jdbcType="INTEGER"/>
    <result column="pt_title" property="title" jdbcType="VARCHAR"/>
  </collection>
</resultMap>

<resultMap id="RichResultMap" type="com.xx.oo.Activity" extends="BaseMap">
  <!--property:对应JavaBean中的字段-->
  <!--ofType:对应JavaBean的类型-->
  <!--javaType:对应返回值的类型-->
  <!--column:对应数据库column的字段,不是JavaBean中的字段-->
  <!--select:对应查询子集的sql-->
  <collection property="templates" ofType="com.xx.oo.Template" javaType="java.util.List" column="id" select="queryTemplateById">
    <id column="pt_id" property="id" jdbcType="INTEGER"/>
    <result column="pt_title" property="title" jdbcType="VARCHAR"/>
  </collection>
</resultMap>

<resultMap id="template" type="com.xx.oo.Template">
  <id column="pt_id" property="id" jdbcType="INTEGER"/>
  <result column="pt_title" property="title" jdbcType="VARCHAR"/>
</resultMap>

需要分页的查询,使用RichResultMap。先定义一个查询子集的sql

<!--这里的#{id}参数就是collection中定义的column字段-->
<select id="queryTemplateById" parameterType="java.lang.Integer" resultMap="template">
  select id pt_id, title pt_title
  from t_activity_template where is_delete=0 and activity_id = #{id}
  order by sort_number desc
</select>
<select id="queryByPage" parameterType="com.xx.oo.ActivityPageRequest" resultMap="RichResultMap">
  SELECT t.*,t1.real_name creator_name
  FROM t_activity t
  left join user t1 on t1.user_id = t.creator
  <where>
    t.is_delete = 0
    <if test="criteria != null and criteria.length()>0">AND (t.activity_name like concat("%",#{criteria},"%"))</if>
  </where>
  ORDER BY t.id desc
</select>

不需要分页的普通查询,使用ResultMap

<select id="queryById" parameterType="java.lang.Integer" resultMap="ResultMap">
  SELECT t.*, t6.id pt_id, t1.title pt_title
  FROM t_activity t
  left join t_activity_template t1 on t.id=t6.activity_id and t1.is_delete=0
  WHERE t.is_delete = 0 AND t.id = #{id}
</select>

上一篇:如何使用Spring+redis实现对session的分布式管理

栏    目:JAVA代码

下一篇:java获取json中的全部键值对实例

本文标题:PageHelper插件实现一对多查询时的分页问题

本文地址:http://www.codeinn.net/misctech/52513.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有