MyBatis if choose 動態(tài) SQL的實(shí)現(xiàn)
動態(tài) SQL
動態(tài) SQL 是 MyBatis 的強(qiáng)大特性之一。如果你使用過 JDBC 或其它類似的框架,你應(yīng)該能理解根據(jù)不同條件拼接 SQL 語句有多痛苦,例如拼接時要確保不能忘記添加必要的空格,還要注意去掉列表最后一個列名的逗號。利用動態(tài) SQL,可以徹底擺脫這種痛苦。
使用動態(tài) SQL 并非一件易事,但借助可用于任何 SQL 映射語句中的強(qiáng)大的動態(tài) SQL 語言,MyBatis 顯著地提升了這一特性的易用性。
如果你之前用過 JSTL 或任何基于類 XML 語言的文本處理器,你對動態(tài) SQL 元素可能會感覺似曾相識。在 MyBatis 之前的版本中,需要花時間了解大量的元素。借助功能強(qiáng)大的基于 OGNL 的表達(dá)式,MyBatis 3 替換了之前的大部分元素,大大精簡了元素種類,現(xiàn)在要學(xué)習(xí)的元素種類比原來的一半還要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
if
使用動態(tài) SQL 最常見情景是根據(jù)條件包含 where 子句的一部分。比如:
<select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE' <if test="title != null"> AND title like #{title} </if> </select>
這條語句提供了可選的查找文本功能。如果不傳入 “title”,那么所有處于 “ACTIVE” 狀態(tài)的 BLOG 都會返回;如果傳入了 “title” 參數(shù),那么就會對 “title” 一列進(jìn)行模糊查找并返回對應(yīng)的 BLOG 結(jié)果(細(xì)心的讀者可能會發(fā)現(xiàn),“title” 的參數(shù)值需要包含查找掩碼或通配符字符)。
如果希望通過 “title” 和 “author” 兩個參數(shù)進(jìn)行可選搜索該怎么辦呢?首先,我想先將語句名稱修改成更名副其實(shí)的名稱;接下來,只需要加入另一個條件即可。
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE' <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
<if test="seat_no != null and seat_no != '' "> AND seat_no = #{seat_no} </if>
<sql id="search"> <if test="userParams.adminType==null or userParams.adminType==''"> and tu.ADMIN_TYPE_ID in(0,1) </if> <if test="userParams.adminType != null and userParams.adminType != ''"> and tu.ADMIN_TYPE_ID=#{userParams.adminType} </if> <if test="userParams.roleId != null and userParams.roleId != ''"> and (select group_concat(ur.ROLE_ID) from t_user u right join t_user_role ur on ur.USER_ID = u.USER_ID, t_role r where r.ROLE_ID = ur.ROLE_ID and u.USER_ID = tu.USER_ID and r.ROLE_ID=#{userParams.roleId}) </if> <if test="userParams.mobile != null and userParams.mobile != ''"> AND tu.MOBILE =#{userParams.mobile} </if> <if test="userParams.username != null and userParams.username != ''"> AND tu.USERNAME like CONCAT('%',#{userParams.username},'%') </if> <if test="userParams.ssex != null and userParams.ssex != ''"> AND tu.SSEX =#{userParams.ssex} </if> <if test="userParams.status != null and userParams.status != ''"> AND tu.STATUS =#{userParams.status} </if> <if test="userParams.deptId != null and userParams.deptId != ''"> AND td.DEPT_ID =#{userParams.deptId} </if> <if test="userParams.createTime != null and userParams.createTime != ''"> AND DATE_FORMAT(tu.CREATE_TIME,'%Y%m%d') BETWEEN substring_index(#{userParams.createTime},'#',1) and substring_index(#{userParams.createTime},'#',-1) </if> </sql>
choose、when、otherwise
有時候,我們不想使用所有的條件,而只是想從多個條件中選擇一個使用。針對這種情況,MyBatis 提供了 choose 元素,它有點(diǎn)像 Java 中的 switch 語句。
還是上面的例子,但是策略變?yōu)椋簜魅肓?“title” 就按 “title” 查找,傳入了 “author” 就按 “author” 查找的情形。若兩者都沒有傳入,就返回標(biāo)記為 featured 的 BLOG(這可能是管理員認(rèn)為,與其返回大量的無意義隨機(jī) Blog,還不如返回一些由管理員精選的 Blog)。
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE' <choose> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select>
<choose> <when test="……"> …… </when> <otherwise> …… </otherwise> </choose>
<select id="findUsersByUser" resultType="cn.soboys.kmall.sys.entity.User"> select tu.USER_ID,tu.USERNAME,tu.SSEX,td.DEPT_NAME,tu.MOBILE,tu.EMAIL,tu.STATUS,tu.CREATE_TIME, td.DEPT_ID from t_user tu left join t_dept td on tu.DEPT_ID = td.DEPT_ID <where> <choose> <when test="userParams.adminType==4"> and tu.ADMIN_TYPE_ID in(2,3) </when> <otherwise> <include refid="search"></include> </otherwise> </choose> </where> </select>
trim、where、set
前面幾個例子已經(jīng)方便地解決了一個臭名昭著的動態(tài) SQL 問題?,F(xiàn)在回到之前的 “if” 示例,這次我們將 “state = ‘ACTIVE’” 設(shè)置成動態(tài)條件,看看會發(fā)生什么。
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
如果沒有匹配的條件會怎么樣?最終這條 SQL 會變成這樣:
SELECT * FROM BLOG WHERE
這會導(dǎo)致查詢失敗。如果匹配的只是第二個條件又會怎樣?這條 SQL 會是這樣:
SELECT * FROM BLOG WHERE AND title like ‘someTitle'
這個查詢也會失敗。這個問題不能簡單地用條件元素來解決。這個問題是如此的難以解決,以至于解決過的人不會再想碰到這種問題。
MyBatis 有一個簡單且適合大多數(shù)場景的解決辦法。而在其他場景中,可以對其進(jìn)行自定義以符合需求。而這,只需要一處簡單的改動:
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </where> </select>
where 元素只會在子元素返回任何內(nèi)容的情況下才插入 “WHERE” 子句。而且,若子句的開頭為 “AND” 或 “OR”,where 元素也會將它們?nèi)コ?/p>
如果 where 元素與你期望的不太一樣,你也可以通過自定義 trim 元素來定制 where 元素的功能。比如,和 where 元素等價的自定義 trim 元素為:
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
prefixOverrides 屬性會忽略通過管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子會移除所有 prefixOverrides 屬性中指定的內(nèi)容,并且插入 prefix 屬性中指定的內(nèi)容。
用于動態(tài)更新語句的類似解決方案叫做 set。set 元素可以用于動態(tài)包含需要更新的列,忽略其它不更新的列。比如:
<update id="updateAuthorIfNecessary"> update Author <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email},</if> <if test="bio != null">bio=#{bio}</if> </set> where id=#{id} </update>
這個例子中,set 元素會動態(tài)地在行首插入 SET 關(guān)鍵字,并會刪掉額外的逗號(這些逗號是在使用條件語句給列賦值時引入的)。
或者,你可以通過使用trim元素來達(dá)到同樣的效果:
<trim prefix="SET" suffixOverrides=","> ... </trim>
注意,我們覆蓋了后綴值設(shè)置,并且自定義了前綴值。
foreach
動態(tài) SQL 的另一個常見使用場景是對集合進(jìn)行遍歷(尤其是在構(gòu)建 IN 條件語句的時候)。比如:
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P <where> <foreach item="item" index="index" collection="list" open="ID in (" separator="," close=")" nullable="true"> #{item} </foreach> </where> </select>
foreach 元素的功能非常強(qiáng)大,它允許你指定一個集合,聲明可以在元素體內(nèi)使用的集合項(xiàng)(item)和索引(index)變量。它也允許你指定開頭與結(jié)尾的字符串以及集合項(xiàng)迭代之間的分隔符。這個元素也不會錯誤地添加多余的分隔符,看它多智能!
提示 你可以將任何可迭代對象(如 List、Set 等)、Map 對象或者數(shù)組對象作為集合參數(shù)傳遞給 foreach。當(dāng)使用可迭代對象或者數(shù)組時,index 是當(dāng)前迭代的序號,item 的值是本次迭代獲取到的元素。當(dāng)使用 Map 對象(或者 Map.Entry 對象的集合)時,index 是鍵,item 是值。
至此,我們已經(jīng)完成了與 XML 配置及映射文件相關(guān)的討論。下一章將詳細(xì)探討 Java API,以便你能充分利用已經(jīng)創(chuàng)建的映射配置。
script
要在帶注解的映射器接口類中使用動態(tài) SQL,可以使用 script 元素。比如:
@Update({"<script>", "update Author", " <set>", " <if test='username != null'>username=#{username},</if>", " <if test='password != null'>password=#{password},</if>", " <if test='email != null'>email=#{email},</if>", " <if test='bio != null'>bio=#{bio}</if>", " </set>", "where id=#{id}", "</script>"}) void updateAuthorValues(Author author);
bind
bind
元素允許你在 OGNL 表達(dá)式以外創(chuàng)建一個變量,并將其綁定到當(dāng)前的上下文。比如:
<select id="selectBlogsLike" resultType="Blog"> <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> SELECT * FROM BLOG WHERE title LIKE #{pattern} </select>
多數(shù)據(jù)庫支持
如果配置了 databaseIdProvider,你就可以在動態(tài)代碼中使用名為 “_databaseId” 的變量來為不同的數(shù)據(jù)庫構(gòu)建特定的語句。比如下面的例子:
<insert id="insert"> <selectKey keyProperty="id" resultType="int" order="BEFORE"> <if test="_databaseId == 'oracle'"> select seq_users.nextval from dual </if> <if test="_databaseId == 'db2'"> select nextval for seq_users from sysibm.sysdummy1" </if> </selectKey> insert into users values (#{id}, #{name}) </insert>
動態(tài) SQL 中的插入腳本語言
MyBatis 從 3.2 版本開始支持插入腳本語言,這允許你插入一種語言驅(qū)動,并基于這種語言來編寫動態(tài) SQL 查詢語句。
可以通過實(shí)現(xiàn)以下接口來插入一種語言:
public interface LanguageDriver { ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql); SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType); SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType); }
實(shí)現(xiàn)自定義語言驅(qū)動后,你就可以在 mybatis-config.xml 文件中將它設(shè)置為默認(rèn)語言:
<typeAliases> <typeAlias type="org.sample.MyLanguageDriver" alias="myLanguage"/> </typeAliases> <settings> <setting name="defaultScriptingLanguage" value="myLanguage"/> </settings>
或者,你也可以使用 lang
屬性為特定的語句指定語言:
<select id="selectBlog" lang="myLanguage"> SELECT * FROM BLOG </select>
或者,在你的 mapper 接口上添加 @Lang
注解:
public interface Mapper { @Lang(MyLanguageDriver.class) @Select("SELECT * FROM BLOG") List<Blog> selectBlog(); }
SQL片段拼接#
我們再寫sql語句的時候往往會有這樣一些要求,一些重復(fù)的sql語句片段,我們不想重復(fù)去寫,那么可以通過sql片段方式去抽離,公共sql然后在需要的地方去引用
MyBatis
中 <sql>
元素用于定義一個 SQL
片段,用于分離一些公共的 SQL 語句,例如:SELECT
關(guān)鍵字和 WHERE
關(guān)鍵字之間的部分。其中:
id
:唯一標(biāo)識符,用于在其他地方使用<include>
標(biāo)簽引用;lang:
設(shè)置字符編碼;databaseId
:指定執(zhí)行該 SQL 語句的數(shù)據(jù)庫ID,數(shù)據(jù)庫ID在 mybatis-cfg.xml 中的 中配置。
同時,你也能夠看見 <sql>
標(biāo)簽中可以使用<include>、<trim>、<where>、<set>、<foreach>、<choose>、<if>、<bind>
等標(biāo)簽定義復(fù)雜的 SQL 片段
簡單使用定義sql片段如下:
<sql id="user_columns"> `user_id`, `name`, `sex`, `age` </sql>
在 <sql>
標(biāo)簽中使用<include>
標(biāo)簽引入定義的sql片段,如下:
<!-- 定義基礎(chǔ)列 --> <sql id="user_base_columns"> `user_id`, `name` </sql> <!-- 定義一個SQL片段 --> <sql id="user_columns"> <include refid="user_base_columns"/>, `sex`, `age` </sql>
場景使用案例如:查詢用戶信息
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.mybatis.sql.demo1.UserMapper"> <!-- 映射結(jié)果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.sql.demo1.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <!-- 定義一個SQL片段 --> <sql id="user_columns"> `user_id`, `name`, `sex`, `age` </sql> <!-- 查詢所有用戶信息 --> <select id="findAll" resultMap="RESULT_MAP"> select <include refid="user_columns" /> from `user` </select> </mapper>
SQL參數(shù)取值和OGNL表達(dá)式
看到我們上面去值參數(shù)通過#{params}
這種方式來去值的其中傳進(jìn)來的參數(shù) #{xx} 就是使用的 OGNL
表達(dá)式。
Mybatis 官方文檔中「XML 映射文件」模塊里邊,有解析到:
說當(dāng)我們使用 #{} 類型參數(shù)符號的時候,其實(shí)就是告訴 Mybatis 創(chuàng)建一個預(yù)處理語句參數(shù),通過 JDBC,這樣的一個參數(shù)在 SQL 中會由一個 "?" 來標(biāo)識,并傳遞到一個新的預(yù)處理語句中。
也就是說當(dāng)我們使用 #{XX} OGNL 表達(dá)式的時候, 它會先幫我們生成一條帶占位符的 SQL 語句,然后在底層幫我們設(shè)置這個參數(shù):ps.setInt(1, id);
OGNL 是 Object-Graph Navigation Language 的縮寫,對象-圖行導(dǎo)航語言,語法為:#{ }。
是不是有點(diǎn)懵,不知道這是個啥?
OGNL 作用是在對象和視圖之間做數(shù)據(jù)的交互,可以存取對象的屬性和調(diào)用對象的方法,通過表達(dá)式可以迭代出整個對象的結(jié)構(gòu)圖
MyBatis常用OGNL表達(dá)式如下:
上述內(nèi)容只是合適在MyBatis中使用的OGNL表達(dá)式,完整的表達(dá)式點(diǎn)擊這里。
MyBatis中可以使用OGNL的地方有兩處:
- 動態(tài)
SQL
表達(dá)式中 ${param}
參數(shù)中
如下例子MySql like 查詢:
<select id="xxx" ...> select id,name,... from country <where> <if test="name != null and name != ''"> name like concat('%', #{name}, '%') </if> </where> </select>
上面代碼中test的值會使用OGNL計算結(jié)果。
例二,通用 like 查詢:
<select id="xxx" ...> select id,name,... from country <bind name="nameLike" value="'%' + name + '%'"/> <where> <if test="name != null and name != ''"> name like #{nameLike} </if> </where> </select>
這里的value值會使用OGNL計算。
注:對<bind參數(shù)的調(diào)用可以通過#{}或 ${} 方式獲取,#{}可以防止注入。
在通用Mapper中支持一種UUID的主鍵,在通用Mapper中的實(shí)現(xiàn)就是使用了標(biāo)簽,這個標(biāo)簽調(diào)用了一個靜態(tài)方法,大概方法如下:
<bind name="username_bind" value='@java.util.UUID@randomUUID().toString().replace("-", "")' />
這種方式雖然能自動調(diào)用靜態(tài)方法,但是沒法回寫對應(yīng)的屬性值,因此使用時需要注意。
${params}
中的參數(shù)
上面like的例子中使用下面這種方式最簡單
<select id="xxx" ...> select id,name,... from country <where> <if test="name != null and name != ''"> name like '${'%' + name + '%'}' </if> </where> </select>
這里注意寫的是${'%' + name + '%'},
而不是%${name}%,
這兩種方式的結(jié)果一樣,但是處理過程不一樣。
在MyBatis
中處理${}
的時候,只是使用OGNL
計算這個結(jié)果值,然后替換SQL中對應(yīng)的${xxx}
,OGNL處理的只是${這里的表達(dá)式}。
這里表達(dá)式可以是OGNL支持的所有表達(dá)式,可以寫的很復(fù)雜,可以調(diào)用靜態(tài)方法返回值,也可以調(diào)用靜態(tài)的屬性值。
例子,條件判斷入?yún)傩灾凳欠癜幼址梢灾苯邮褂?nbsp;contains
判斷
<foreach collection="list" item="item" index="index" separator="AND" open="(" close=")"> <choose> <when test='item.cname.contains("select") or item.cname.contains("checkbox") or item.cname.contains("date")'> <if test='item.cname.contains("select") or item.cname.contains("checkbox")'> find_in_set(#{item.value},base.${item.cname}) </if> <if test='item.cname.contains("date")'> DATE_FORMAT(base.${item.cname},'%Y-%m-%d') = DATE_FORMAT(#{item.value},'%Y-%m-%d') </if> </when> <otherwise> base.${item.cname} = #{item.value} </otherwise> </choose> </foreach>
到此這篇關(guān)于MyBatis if choose 動態(tài) SQL的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis 動態(tài) SQL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot默認(rèn)文件緩存(easy-captcha?驗(yàn)證碼)
這篇文章主要介紹了springboot的文件緩存(easy-captcha?驗(yàn)證碼),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06Spring依賴注入中的@Resource與@Autowired詳解
這篇文章主要介紹了Spring依賴注入中的@Resource與@Autowired詳解,提到Spring依賴注入,大家最先想到應(yīng)該是@Resource和@Autowired,對于Spring為什么要支持兩個這么類似的注解卻未提到,屬于知其然而不知其所以然,本文就來做詳細(xì)講解,需要的朋友可以參考下2023-09-09Spring Security實(shí)現(xiàn)自定義訪問策略
本文介紹Spring Security實(shí)現(xiàn)自定義訪問策略,當(dāng)根據(jù)誰訪問哪個域?qū)ο笞龀霭踩珱Q策時,您可能需要一個自定義的訪問決策投票者,幸運(yùn)的是,Spring Security有很多這樣的選項(xiàng)來實(shí)現(xiàn)訪問控制列表(ACL)約束,下面就來學(xué)習(xí)Spring Security自定義訪問策略,需要的朋友可以參考下2022-02-02Java通過調(diào)用C/C++實(shí)現(xiàn)的DLL動態(tài)庫——JNI的方法
這篇文章主要介紹了Java通過調(diào)用C/C++實(shí)現(xiàn)的DLL動態(tài)庫——JNI的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2018-01-01Spring boot如何基于攔截器實(shí)現(xiàn)訪問權(quán)限限制
這篇文章主要介紹了Spring boot如何基于攔截器實(shí)現(xiàn)訪問權(quán)限限制,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10java實(shí)現(xiàn)excel和txt文件互轉(zhuǎn)
本篇文章主要介紹了java實(shí)現(xiàn)excel和txt文件互轉(zhuǎn)的相關(guān)知識。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04詳解Spring?Boot中@PostConstruct的使用示例代碼
在Java中,@PostConstruct是一個注解,通常用于標(biāo)記一個方法,它表示該方法在類實(shí)例化之后(通過構(gòu)造函數(shù)創(chuàng)建對象之后)立即執(zhí)行,這篇文章主要介紹了詳解Spring?Boot中@PostConstruct的使用,需要的朋友可以參考下2023-09-09