項目中經(jīng)常會使用到一對多的查詢場景,但是pagehelper對這種嵌套查詢的支持不夠,如果是一對多的列表查詢,返回的分頁結(jié)果是不對的
參考github上的說明:https://github.com/pagehelper/mybatis-pagehelper/blob/master/wikis/zh/important.md
對于一對多的列表查詢,有兩種方式解決
1、在代碼中處理。單獨修改分頁查詢的resultmap,刪除collection標簽,然后在代碼中遍歷結(jié)果,查詢子集
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:對應(yīng)javabean中的字段--> <!--oftype:對應(yīng)javabean的類型--> <!--javatype:對應(yīng)返回值的類型--> <!--column:對應(yīng)數(shù)據(jù)庫column的字段,不是javabean中的字段--> <!--select:對應(yīng)查詢子集的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}參數(shù)就是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> |
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://segmentfault.com/a/1190000018825136