系列文章目錄
1、mybatis簡介及數據庫連接池
2、mybatis中selectOne的使用
3、mybatis簡單使用
4、mybatis中resultMap結果集的使用
Mybatis實用教程之XML實現動態sql
- 系列文章目錄
- 前言
- 1. 動態條件查詢
- 2. 動態更新語句
- 3. 動態插入語句
- 4、其他標簽的使用
前言
當編寫 MyBatis 中復雜動態 SQL 語句時,使用 XML 格式是一種非常靈活的方式。這樣做可以根據不同條件動態生成 SQL 查詢,更新或刪除語句。以下是一篇簡要的教程,詳細介紹如何使用 MyBatis XML 來編寫動態 SQL。
1. 動態條件查詢
假設有一個 User
實體,有 id
、username
和 email
字段,我們希望根據不同條件查詢用戶信息。
<!-- 在 Mapper XML 文件中編寫動態 SQL 查詢 -->
<select id="selectUsers" resultType="User">SELECT * FROM users<where><if test="id != null">AND id = #{id}</if><if test="username != null and username != ''">AND username = #{username}</if><if test="email != null and email != ''">AND email = #{email}</if></where>
</select>
<where>
標簽用于將動態生成的條件組合到 WHERE 子句中。<if>
標簽根據條件的存在與否來動態生成查詢條件。
上面的方法可以根據id、username、email進行條件查詢,當test后面的語句為true的時候,會將if標簽內的語句拼接。
2. 動態更新語句
假設我們想根據不同的條件更新用戶信息。
<!-- 在 Mapper XML 文件中編寫動態 SQL 更新 -->
<update id="updateUser" parameterType="User">UPDATE users<set><if test="username != null">username = #{username},</if><if test="email != null">email = #{email},</if></set>WHERE id = #{id}
</update>
<set>
標簽用于指定要更新的字段。<if>
標簽根據條件動態設置要更新的字段。
3. 動態插入語句
如果要根據不同情況插入不同的字段,也可以使用動態 SQL。
<!-- 在 Mapper XML 文件中編寫動態 SQL 插入 -->
<insert id="insertUser" parameterType="User">INSERT INTO users<trim prefix="(" suffix=")" suffixOverrides=","><if test="id != null">id,</if><if test="username != null and username != ''">username,</if><if test="email != null and email != ''">email,</if></trim><trim prefix="VALUES (" suffix=")" suffixOverrides=","><if test="id != null">#{id},</if><if test="username != null and username != ''">#{username},</if><if test="email != null and email != ''">#{email},</if></trim>
</insert>
<trim>
標簽用于動態設置插入的字段和對應的值,當trim標簽內的內容為空時,不會添加前綴。prefix
和suffix
屬性用于指定插入語句的前綴和后綴。suffixOverrides
屬性用于去除最后一個不必要的逗號。
4、其他標簽的使用
基礎的語法使用如下所示。choose、when、otherwise 有點像if-else if -else的感覺
<!-- 使用 choose、when、otherwise 標簽實現條件選擇 -->
<select id="getUserByIdOrUsername" resultType="User">SELECT * FROM users<where><choose><when test="id != null">AND id = #{id}</when><when test="username != null and username != ''">AND username = #{username}</when><otherwise>AND 1=1</otherwise></choose></where>
</select><!-- 使用 foreach 標簽進行遍歷操作 -->
<select id="getUsersByIdList" resultType="User">SELECT * FROM usersWHERE id IN<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
</select>