MyBatis trim標簽核心用法代碼實戰(zhàn)
更新時間:2026年03月09日 09:52:04 作者:老趙全棧實戰(zhàn)
MyBatis的<trim>標簽用于動態(tài)SQL拼接,處理SQL前后綴和多余關鍵字,避免語法錯誤,提升代碼可維護性,本文給大家介紹MyBatis trim標簽核心用法代碼實戰(zhàn),感興趣的朋友跟隨小編一起看看吧
?? 今日知識點
- 核心主題:MyBatis
<trim>標簽基本使用、動態(tài)SQL拼接、WHERE條件優(yōu)化 - 適用場景:動態(tài)查詢條件構(gòu)建、批量更新語句、靈活的SQL片段組裝
- 一句話總結(jié):
<trim>標簽智能處理SQL前后綴和多余關鍵字,讓動態(tài)SQL更優(yōu)雅、更可靠
?? 核心原理(簡化版)
<trim>標簽通過配置前綴、后綴、去除關鍵字,自動處理動態(tài)SQ 的拼接邏輯- 核心邏輯:根據(jù)標簽內(nèi)容是否為空,智能添加或刪除指定的SQL片段
- 核心價值:替代手動拼接SQL,避免語法錯誤(如多余的AND、OR、SET),提升代碼可維護性
?? 代碼實戰(zhàn)(可直接復制運行)
1. 環(huán)境配置
<!-- Maven依賴(Spring Boot項目默認包含) -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<!-- 或使用 MyBatis Plus(兼容原生 MyBatis) -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>2. 核心用法示例
示例一:動態(tài) WHERE 條件查詢
// 實體類
@Data
public class User {
private Long id;
private String username;
private String email;
private Integer age;
private Integer status;
}<!-- Mapper XML文件 -->
<mapper namespace="com.example.mapper.UserMapper">
<!-- 基礎結(jié)果映射 -->
<resultMap id="BaseResultMap" type="com.example.entity.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="email" property="email"/>
<result column="age" property="age"/>
<result column="status" property="status"/>
</resultMap>
<!-- 動態(tài)查詢:使用 trim 處理 WHERE 條件 -->
<select id="selectByCondition" parameterType="com.example.entity.User" resultMap="BaseResultMap">
SELECT * FROM user
<trim prefix="WHERE" prefixOverrides="AND|OR">
<!-- 如果 username 不為空,添加條件 -->
<if test="username != null and username != ''">
AND username LIKE CONCAT('%', #{username}, '%')
</if>
<!-- 如果 email 不為空,添加條件 -->
<if test="email != null and email != ''">
AND email = #{email}
</if>
<!-- 如果 age 不為空,添加條件 -->
<if test="age != null">
AND age > #{age}
</if>
<!-- 如果status不為空,添加條件 -->
<if test="status != null">
AND status = #{status}
</if>
</trim>
ORDER BY id DESC
</select>
</mapper>// Mapper接口
@Mapper
public interface UserMapper {
List<User> selectByCondition(@Param("user") User user);
}
// 測試代碼
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectByCondition() {
// 測試1:只有 username 條件
User condition1 = new User();
condition1.setUsername("john");
List<User> result1 = userMapper.selectByCondition(condition1);
System.out.println("查詢結(jié)果1: " + result1.size());
// 測試2:多個條件組合
User condition2 = new User();
condition2.setUsername("alice");
condition2.setAge(18);
condition2.setStatus(1);
List<User> result2 = userMapper.selectByCondition(condition2);
System.out.println("查詢結(jié)果2: " + result2.size());
// 測試3:無條件(返回所有)
User condition3 = new User();
List<User> result3 = userMapper.selectByCondition(condition3);
System.out.println("查詢結(jié)果3: " + result3.size());
}
}生成的SQL示例:
-- 測試1:只有 username 條件(自動去除開頭的 AND)
SELECT * FROM user
WHERE username LIKE CONCAT('%', 'john', '%')
ORDER BY id DESC
-- 測試2:多個條件組合
SELECT * FROM user
WHERE username LIKE CONCAT('%', 'alice', '%')
AND age > 18
AND status = 1
ORDER BY id DESC
-- 測試3:無條件(不生成 WHERE 子句)
SELECT * FROM user
ORDER BY id DESC示例二:動態(tài) UPDATE 語句
<!-- 動態(tài)更新:使用 trim 處理 SET 關鍵字 -->
<update id="updateSelective" parameterType="com.example.entity.User">
UPDATE user
<trim prefix="SET" suffixOverrides=",">
<if test="username != null and username != ''">
username = #{username},
</if>
<if test="email != null and email != ''">
email = #{email},
</if>
<if test="age != null">
age = #{age},
</if>
<if test="status != null">
status = #{status},
</if>
</trim>
WHERE id = #{id}
</update>// 測試代碼
@Test
public void testUpdateSelective() {
// 準備數(shù)據(jù)
User user = new User();
user.setId(1L);
user.setUsername("updated_user");
user.setEmail("new@example.com");
// 只更新 username 和 email,age 和 status 保持不變
int rows = userMapper.updateSelective(user);
System.out.println("更新行數(shù):" + rows);
}生成的SQL示例:
-- 只更新非空字段(自動去除末尾的逗號)
UPDATE user
SET username = 'updated_user',
email = 'new@example.com'
WHERE id = 1
3. trim標簽屬性詳解(4個核心,記牢即可)
<!-- 1. prefix:在trim標簽內(nèi)容前添加的前綴 -->
<trim prefix="WHERE">
<!-- 內(nèi)容 -->
</trim>
<!-- 生成:WHERE (內(nèi)容) -->
<!-- 2. suffix:在 trim 標簽內(nèi)容后添加的后綴 -->
<trim suffix="ORDER BY id">
<!-- 內(nèi)容 -->
</trim>
<!-- 生成:(內(nèi)容) ORDER BY id -->
<!-- 3. prefixOverrides:要去除的前綴(支持正則表達式,用 | 分隔) -->
<trim prefix="WHERE" prefixOverrides="AND|OR">
<if test="condition1">AND col1 = val1</if>
<if test="condition2">AND col2 = val2</if>
</trim>
<!-- 生成:WHERE col1 = val1 AND col2 = val2 -->
<!-- 4. suffixOverrides:要去除的后綴(支持正則表達式,用 | 分隔) -->
<trim prefix="SET" suffixOverrides=",">
<if test="col1 != null">col1 = val1,</if>
<if test="col2 != null">col2 = val2,</if>
</trim>
<!-- 生成:SET col1 = val1, col2 = val2 -->?? 避坑指南(簡潔重點)
1.核心坑1:prefixOverrides未正確配置導致SQL語法錯誤
<!-- ? 錯誤寫法:忘記配置 prefixOverrides -->
<select id="selectBad" resultMap="BaseResultMap">
SELECT * FROM user
<trim prefix="WHERE">
<if test="username != null">
AND username = #{username} <!-- 第一個條件前有 AND -->
</if>
</trim>
</select>
<!-- 生成錯誤SQL:SELECT * FROM user WHERE AND username = ? -->
<!-- ? 正確寫法:配置 prefixOverrides="AND|OR" -->
<select id="selectGood" resultMap="BaseResultMap">
SELECT * FROM user
<trim prefix="WHERE" prefixOverrides="AND|OR">
<if test="username != null">
AND username = #{username}
</if>
</trim>
</select>
<!-- 生成正確SQL:SELECT * FROM user WHERE username = ? -->2.核心坑2:suffixOverrides未去除多余逗號
<!-- ? 錯誤寫法:忘記配置 suffixOverrides -->
<update id="updateBad">
UPDATE user
<trim prefix="SET">
<if test="username != null">
username = #{username}, <!-- 最后一個字段后有逗號 -->
</if>
</trim>
WHERE id = #{id}
</update>
<!-- 生成錯誤SQL:UPDATE user SET username = ?, -->
<!-- ? 正確寫法:配置 suffixOverrides="," -->
<update id="updateGood">
UPDATE user
<trim prefix="SET" suffixOverrides=",">
<if test="username != null">
username = #{username},
</if>
</trim>
WHERE id = #{id}
</update>
<!-- 生成正確SQL:UPDATE user SET username = ? WHERE id = ? -->3.核心坑3:trim嵌套使用時的注意事項
<!-- ? 復雜場景:trim 可以嵌套使用 -->
<select id="selectComplex" resultMap="BaseResultMap">
SELECT * FROM user
<trim prefix="WHERE" prefixOverrides="AND|OR">
<!-- 外層 trim 處理 WHERE -->
<if test="query != null">
<!-- 內(nèi)層 trim 處理分組條件 -->
<trim prefix="(" prefixOverrides="AND|OR" suffix=")">
<if test="query.username != null">
AND username LIKE #{query.username}
</if>
<if test="query.email != null">
AND email LIKE #{query.email}
</if>
</trim>
</if>
<if test="status != null">
AND status = #{status}
</if>
</trim>
</select>
<!-- 生成SQL:SELECT * FROM user WHERE (username LIKE ? AND email LIKE ?) AND status = ? -->4.核心坑4:trim vs where/set標簽選擇
<!-- trim 標簽:最靈活,可自定義前后綴和去除規(guī)則 -->
<trim prefix="WHERE" prefixOverrides="AND|OR" suffix="LIMIT 10">
<!-- 復雜場景 -->
</trim>
<!-- where 標簽:trim的簡化版,固定處理WHERE和AND/OR -->
<where>
<if test="condition1">AND col1 = val1</if>
<if test="condition2">AND col2 = val2</if>
</where>
<!-- 等價于:<trim prefix="WHERE" prefixOverrides="AND|OR"> -->
<!-- set 標簽:trim的簡化版,固定處理SET和逗號 -->
<set>
<if test="col1 != null">col1 = val1,</if>
<if test="col2 != null">col2 = val2,</if>
</set>
<!-- 等價于:<trim prefix="SET" suffixOverrides=","> -->
<!-- 最佳實踐:簡單場景用 where/set,復雜場景用 trim -->? 今日總結(jié)
<trim>標簽核心是"智能拼接",自動處理 SQL 前后綴和多余關鍵字,避免語法錯誤- 4個核心屬性:
prefix(前綴)、suffix(后綴)、prefixOverrides(去前綴)、suffixOverrides(去后綴) - 實用性強:動態(tài)查詢、批量更新、復雜條件組裝等場景都能大幅提升 SQL 可維護性
- 最佳實踐:簡單場景用
<where>/<set>簡化版,復雜場景用<trim>完整版
到此這篇關于MyBatis trim標簽核心用法代碼實戰(zhàn)的文章就介紹到這了,更多相關MyBatis trim標簽用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot打包無法讀取yml、properties等配置文件的解決
這篇文章主要介紹了springboot打包無法讀取yml、properties等配置文件的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
Spring?Cloud?中使用?Sentinel?實現(xiàn)服務限流的兩種方式
這篇文章主要介紹了Spring?Cloud?中使用?Sentinel?實現(xiàn)服務限流的方式,通過示例代碼主要介紹了Sentinel的兩種實現(xiàn)限流的方式,需要的朋友可以參考下2024-03-03
Java?JDK?Validation?注解解析與使用方法驗證
Jakarta?Validation提供了一種聲明式、標準化的方式來驗證Java對象,與框架無關,可以方便地集成到各種Java應用中,本文給大家介紹Java?JDK?Validation?注解解析與使用,感興趣的朋友一起看看吧2025-09-09
BeanUtils.copyProperties復制對象結(jié)果為空的原因分析
這篇文章主要介紹了BeanUtils.copyProperties復制對象結(jié)果為空的原因分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringCloud可視化鏈路追蹤系統(tǒng)Zipkin部署過程
這篇文章主要介紹了SpringCloud可視化鏈路追蹤系統(tǒng)Zipkin部署過程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03

