MyBatis實(shí)現(xiàn)動(dòng)態(tài)SQL的實(shí)現(xiàn)方法
MyBatis 最強(qiáng)大的特性之一就是它的動(dòng)態(tài)語句功能。如果您以前有使用JDBC或者類似框架的 經(jīng)歷,您就會(huì)明白把SQL語句條件連接在一起是多么的痛苦,要確保不能忘記空格或者不要在 columns列后面省略一個(gè)逗號(hào)等。動(dòng)態(tài)語句能夠完全解決掉這些痛苦。
盡管與動(dòng)態(tài)SQL一起工作不是在開一個(gè)party,但是MyBatis確實(shí)能通過在任何映射SQL語句中 使用強(qiáng)大的動(dòng)態(tài)SQL來改進(jìn)這些狀況。
if 元素
if元素條件判斷,動(dòng)態(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”如果它包含的標(biāo)簽中有內(nèi)容返回的話。此外,如果返回的內(nèi)容 以“AND” 或者 “OR”開頭,它會(huì)把“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元素
有時(shí)候我們不想應(yīng)用所有的條件,而是想從多個(gè)選項(xiàng)中選擇一個(gè)。與 java 中的 switch 語句 相似,MyBatis 提供了一個(gè) choose 元素。
when元素
當(dāng)when里面的條件成立時(shí),執(zhí)行when標(biāo)簽內(nèi)的語句
<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元素
當(dāng)所有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內(nèi)的if有成立的就添加一個(gè)前綴用prefix=""定義,沒有就不添加。
trim元素也可以去掉where后面指定的關(guān)鍵字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元素
在動(dòng)態(tài)update語句里相似的解決方式叫做set,這個(gè)set元素能夠動(dòng)態(tài)地更新列。
set 元素將動(dòng)態(tài)的配置set關(guān)鍵字,也用來剔除追加到條件末尾的任何不相關(guān)的逗號(hào)。
<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>
當(dāng)然了,聰明的你肯定想知道等同的 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>
注意這種情況,我們剔除了一個(gè)后綴, 同時(shí)追加了一個(gè)前綴 。
Foreach 元素
另一個(gè)動(dòng)態(tài) SQL 經(jīng)常使用到的功能是集合迭代,通常用在 in條件句
foreach 元素非常強(qiáng)大,允許您指定一個(gè)集合,申明能夠用在元素體內(nèi)的項(xiàng)和索引變量。也 允許您指定開始和結(jié)束的字符,也可以加入一個(gè)分隔符到迭代器之間。這個(gè)元素的聰明之處在于 它不會(huì)意外地追加額外的分隔符。
<select id="findStudentByAge" resultMap="studentInfo"> select * from t_student where age in <foreach collection="list" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
測(cè)試方法如下:
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結(jié)果:select * from t_student where age in (item,item),顯示age為21、23的學(xué)生信息。
Settings 元素
Setting 元素下是些非常重要的設(shè)置選項(xiàng),用于設(shè)置和改變 MyBatis 運(yùn)行中的行為。下面的 表格列出了 Setting 元素支持的屬性、默認(rèn)值及其功能。
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(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 配置,那不可避免地會(huì)遇到一些對(duì) XML 來說是特殊的字符。如小于號(hào) “<”,因?yàn)?XML 解析器會(huì)認(rèn)為是一個(gè)新元素的開始,因此要進(jìn)行轉(zhuǎn)義。這里有兩個(gè)方法:
1 使用轉(zhuǎn)義實(shí)體
下面是五個(gè)在 XML 文檔中預(yù)定義好的轉(zhuǎn)義實(shí)體 :
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo"> select * from t_student where age $lt; 23 </select>
2 使用 CDATA 部件
一個(gè) CDATA 部件以"“標(biāo)記結(jié)束。在”"之間 的特殊字符的意義都不起作用,而轉(zhuǎn)變?yōu)槠胀ㄗ址畠?nèi)容。
一般地,在 MyBatis 的 XML 映射語句配置文件中,如果 SQL 語句有特殊字符,那么使用 CDTA 部件括起來,如:
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo"> <![CDATA[ select * from t_student where age = 23 ]]> </select>
而在動(dòng)態(tài) SQL 各元素的測(cè)試語句中,在元素的屬性中不能再嵌套其它元素或包含 CDATA 部 件,因此只能使用轉(zhuǎn)義實(shí)體, 如:
<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>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
如何將JSON字符串?dāng)?shù)組轉(zhuǎn)對(duì)象集合
這篇文章主要介紹了如何將JSON字符串?dāng)?shù)組轉(zhuǎn)對(duì)象集合,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06使用JPA中@Query 注解實(shí)現(xiàn)update 操作方法(必看)
下面小編就為大家?guī)硪黄褂肑PA中@Query 注解實(shí)現(xiàn)update 操作方法(必看)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06Flutter實(shí)現(xiàn)容器組件、圖片組件 的代碼
容器組件(Container)可以理解為在Android中的RelativeLayout或LinearLayout等,在其中你可以放置你想布局的元素控件,從而形成最終你想要的頁面布局。這篇文章主要介紹了Flutter實(shí)現(xiàn)容器組件、圖片組件 的代碼,需要的朋友可以參考下2019-07-07