项目中经常会使用到一对多的 查询 场景,但是pagehelper对这种嵌套查询的支持不够,如果是一对多的列表查询,返回的 分页 结果是不对的
参考github上的说明: https://github测试数据/pagehelper/mybatis-pagehelper/blob/master/wikis/zh/important.md
对于一对多的列表查询,有两种方式解决
1、在代码中处理。单独修改分页查询的resultmap,删除collection标签,然后在代码中遍历结果,查询子集
2、使用mybatis提供的方法解决,具体如下
定义两个resultmap,一个给分页查询使用,一个给其余查询使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!--这里的#{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
1 2 3 4 5 6 |
<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> |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://segmentfault测试数据/a/1190000018825136
查看更多关于PageHelper插件实现一对多查询时的分页问题的详细内容...