springboot+mybatis按條件分頁查詢多張表的項目實踐
背景
假如同 mysql 數(shù)據(jù)源下有如下幾張表:
- 用戶基礎(chǔ)信息表
- 用戶地址表
- 用戶學(xué)歷信息表
我希望做分頁查詢用戶數(shù)據(jù),用戶數(shù)據(jù)為各個表內(nèi)信息的匯總,并且這個分頁查詢會根據(jù)各種條件來查詢
那么通常該如何做呢?
方案推薦
一般情況下通用推薦(下面主講):
使用 join 進行多表連接查詢,使用 pagehelper 分頁插件,通過 MyBatis 的 <resultMap> 和 JOIN 語句實現(xiàn)多表關(guān)聯(lián),使用 MyBatis 動態(tài) SQL 標(biāo)簽(如 )處理條件組合
其他方案:
- 方式一:將高頻查詢字段冗余到主表,形成寬表,此方案犧牲空間換取性能,以后直接分頁查詢一張表即可
- 方式二:分步驟來查詢,在代碼層面進行數(shù)據(jù)組裝
創(chuàng)建 DTO
創(chuàng)建 dto 做查詢數(shù)據(jù)接收的對象
public class UserQueryDTO {
private String name; // 用戶姓名(模糊查詢)
private String province; // 省份條件
private String degree; // 學(xué)歷條件
}
創(chuàng)建 Mapper
創(chuàng)建一個 mapper 接口 selectUserWithConditions
創(chuàng)建對應(yīng) 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);
}
到此這篇關(guān)于springboot+mybatis按條件分頁查詢多張表的項目實踐的文章就介紹到這了,更多相關(guān)springboot mybatis 條件多表分頁查詢 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring編程式和聲明式事務(wù)實例講解小結(jié)
這篇文章主要介紹了Spring編程式和聲明式事務(wù)實例講解小結(jié),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Spring boot實現(xiàn)一個簡單的ioc(1)
這篇文章主要為大家詳細介紹了Spring boot實現(xiàn)一個簡單的ioc,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
java 下執(zhí)行mysql 批量插入的幾種方法及用時
java 下執(zhí)行mysql 批量插入的幾種方法及用時,1000次插入方法的比較。2013-04-04
SpringBoot內(nèi)置數(shù)據(jù)源的持久化與解決方案
數(shù)據(jù)源的配置 我們先基于SpringBoot默認的HikariDataSource數(shù)據(jù)源,導(dǎo)入JDBC場景,看看SpringBoot幫我們自動配置了什么,下面我們來了解SpringBoot內(nèi)置數(shù)據(jù)源持久化2022-07-07

