1. 程式人生 > 程式設計 >MyBatis實現動態SQL的實現方法

MyBatis實現動態SQL的實現方法

MyBatis 最強大的特性之一就是它的動態語句功能。如果您以前有使用JDBC或者類似框架的 經歷,您就會明白把SQL語句條件連線在一起是多麼的痛苦,要確保不能忘記空格或者不要在 columns列後面省略一個逗號等。動態語句能夠完全解決掉這些痛苦。

​儘管與動態SQL一起工作不是在開一個party,但是MyBatis確實能通過在任何對映SQL語句中 使用強大的動態SQL來改進這些狀況。

if 元素

if元素條件判斷,動態 SQL 最常做的事就是有條件地包括 where 子句。例如:

<select id=”findActiveBlogWithTitleLike” parameterType=”Blog” resultType=”Blog”>
 SELECT * FROM BLOG WHERE state = ‘ACTIVE'
 <if test=”title != null”>
 AND title like #{title}
 </if>
</select>

where元素

where元素知道插入“where”如果它包含的標籤中有內容返回的話。此外,如果返回的內容 以“AND” 或者 “OR”開頭,它會把“AND” 或者 “OR”去掉。

<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
 select * from t_student
 <where>
 <if test="name!=null">
  and name=#{name}
 </if>
 <if test="age!=null">
  and age=#{age}
 </if>
 </where>
</select>

choose元素

有時候我們不想應用所有的條件,而是想從多個選項中選擇一個。與 java 中的 switch 語句 相似,MyBatis 提供了一個 choose 元素。

when元素

當when裡面的條件成立時,執行when標籤內的語句

<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
 select * from t_student
 <where>
 <choose>
  <when test="name!=null">
  and name=#{name}
  </when>
  <when test="age!=null">
  and age=#{age}
  </when>
 </choose>
 </where>
</select>

otherwise元素

當所有when都不成立了,執行otherwise

<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
 select * from t_student
 <where>
 <choose>
  <when test="name!=null">
  and name=#{name}
  </when>
  <when test="age!=null">
  and age=#{age}
  </when>
  <otherwise>
  and name='jim'
  </otherwise>
 </choose>
 </where>
</select>

trim元素

如果 where 元素的行為並沒有完全按您想象的那樣,您還可以使用 trim 元素來自定義。

​trim內的if有成立的就新增一個字首用prefix=""定義,沒有就不新增。

​trim元素也可以去掉where後面指定的關鍵字and或者or等等,用prefixOverrides=""定義

<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
 select * from t_student
 <trim prefix="where" prefixOverrides="and">
 <if test="name!=null">
  and name=#{name}
 </if>
 <if test="age!=null">
  and age=#{age}
 </if>
 </trim>
</select>

set元素

在動態update語句裡相似的解決方式叫做set,這個set元素能夠動態地更新列。

set 元素將動態的配置set關鍵字,也用來剔除追加到條件末尾的任何不相關的逗號。

<update id="updateStudent" parameterType="Student">
 update t_student
 <set>
 <if test="name!=null">
  name=#{name},</if>
 <if test="age!=null">
  age=#{age},</if>
 </set>
 where id=#{id}
</update>

當然了,聰明的你肯定想知道等同的 trim 元素該怎麼寫吧,它就像這樣 :

<update id="updateStudent" parameterType="Student">
 update t_student
 <trim prefix="set" prefixOverrides=",">
 <if test="name!=null">
  name=#{name},</if>
 </trim>
 where id=#{id}
</update>

注意這種情況,我們剔除了一個字尾, 同時追加了一個字首 。

Foreach 元素

另一個動態 SQL 經常使用到的功能是集合迭代,通常用在 in條件句

foreach 元素非常強大,允許您指定一個集合,申明能夠用在元素體內的項和索引變數。也 允許您指定開始和結束的字元,也可以加入一個分隔符到迭代器之間。這個元素的聰明之處在於 它不會意外地追加額外的分隔符。

<select id="findStudentByAge" resultMap="studentInfo">
 select * from t_student where age in
 <foreach collection="list" item="item" open="(" separator="," close=")">
 #{item}
 </foreach>
</select>

測試方法如下:

public void findStudentByAge() {
 SqlSession sqlSession = null;
 try {
 sqlSession = MyBatisUtil.getsqlSession();
 StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
 List<Integer> list= new ArrayList<Integer>();
 list.add(21);
 list.add(23);
 List<Student> liststudent =studentDao.findStudentByAge(list);
 System.out.println(liststudent);
 } catch (Exception e) {
 e.printStackTrace();
 }
}
 

輸出的sql結果:select * from t_student where age in (item,item),顯示age為21、23的學生資訊。

Settings 元素

Setting 元素下是些非常重要的設定選項,用於設定和改變 MyBatis 執行中的行為。下面的 表格列出了 Setting 元素支援的屬性、預設值及其功能。

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-vuQc9cUw-1576746278488)(E:\javaEE筆記\img\QQ瀏覽器截圖20191218153217.png)]

完整配置例子:

<settings>
 <setting name="cacheEnabled" value="true"/>
 <setting name="lazyLoadingEnabled" value="true"/>
 <setting name="multipleResultSetsEnabled" value="true"/>
 <setting name="useColumnLabel" value="true"/>
 <setting name="useGeneratedKeys" value="false"/>
 <setting name="enhancementEnabled" value="false"/>
 <setting name="defaultExecutorType" value="SIMPLE"/>
 <setting name="defaultStatementTimeout" value="25000"/>
</settings>

XML 中的特殊字元

如果 MyBatis 使用 XML 配置,那不可避免地會遇到一些對 XML 來說是特殊的字元。如小於號 “<”,因為 XML 解析器會認為是一個新元素的開始,因此要進行轉義。這裡有兩個方法:

1 使用轉義實體

下面是五個在 XML 文件中預定義好的轉義實體 :

[外鏈圖片轉存失敗,建議將圖片儲存下來直接上傳

<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
 select * from t_student where age $lt; 23
</select>

2 使用 CDATA 部件

一個 CDATA 部件以"“標記結束。在”"之間 的特殊字元的意義都不起作用,而轉變為普通字串內容。

一般地,在 MyBatis 的 XML 對映語句配置檔案中,如果 SQL 語句有特殊字元,那麼使用 CDTA 部件括起來,如:

<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
 <![CDATA[
 select * from t_student where age = 23
 ]]> 
</select>

而在動態 SQL 各元素的測試語句中,在元素的屬性中不能再巢狀其它元素或包含 CDATA 部 件,因此只能使用轉義實體, 如:

<select id="selectAuthor_use_where" parameterType="Blog" resultType="Author">
 select * from author
 <where>
 <if test="authorId != null
  and authorId >= 1
  and authorId <= 5">
 id = #{authorId}
 </if>
 </where>
</select> 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。