MyBatis實現動態(tài)SQL的實現方法
MyBatis 最強大的特性之一就是它的動態(tài)語句功能。如果您以前有使用JDBC或者類似框架的 經歷,您就會明白把SQL語句條件連接在一起是多么的痛苦,要確保不能忘記空格或者不要在 columns列后面省略一個逗號等。動態(tài)語句能夠完全解決掉這些痛苦。
盡管與動態(tài)SQL一起工作不是在開一個party,但是MyBatis確實能通過在任何映射SQL語句中 使用強大的動態(tài)SQL來改進這些狀況。
if 元素
if元素條件判斷,動態(tài) 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里面的條件成立時,執(zhí)行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都不成立了,執(zhí)行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元素
在動態(tài)update語句里相似的解決方式叫做set,這個set元素能夠動態(tài)地更新列。
set 元素將動態(tài)的配置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> <if test="age!=null"> age=#{age}, </if> </trim> where id=#{id} </update>
注意這種情況,我們剔除了一個后綴, 同時追加了一個前綴 。
Foreach 元素
另一個動態(tài) 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 部件以"“標記結束。在”"之間 的特殊字符的意義都不起作用,而轉變?yōu)槠胀ㄗ址畠热荨?/p>
一般地,在 MyBatis 的 XML 映射語句配置文件中,如果 SQL 語句有特殊字符,那么使用 CDTA 部件括起來,如:
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo"> <![CDATA[ select * from t_student where age = 23 ]]> </select>
而在動態(tài) 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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
使用JPA中@Query 注解實現update 操作方法(必看)
下面小編就為大家?guī)硪黄褂肑PA中@Query 注解實現update 操作方法(必看)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06