PageHelper插件實現一對多查詢時的分頁問題
項目中經常會使用到一對多的查詢場景,但是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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java 8 Stream Api 中的 map和 flatMap 操作方法
Java 8提供了非常好用的 Stream API ,可以很方便的操作集合。今天通過這篇文章給大家分享Java 8 Stream Api 中的 map和 flatMap 操作方法,需要的朋友可以參考下2019-11-11Spring BeanPostProcessor源碼示例解析
這篇文章主要為大家介紹了Spring BeanPostProcessor源碼示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01分析java并發(fā)中的wait notify notifyAll
一個線程修改一個對象的值,而另一個線程則感知到了變化,然后進行相應的操作,這就是wait()、notify()和notifyAll()方法的本質。本文將詳細來介紹它們概念實現以及區(qū)別2021-06-06Spring?Boot實現JWT?token自動續(xù)期的實現
本文主要介紹了Spring?Boot實現JWT?token自動續(xù)期,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12