大家基本上都知道如何使用 MyBatis 執(zhí)行任意 SQL,使用方法很簡單,例如在一個 XXMapper.xml 中:
1
2
3
|
< select id= "executeSql" resultType= "map" > ${_parameter} </ select > |
你可以如下調(diào)用:
1
|
sqlSession.selectList( "executeSql" , "select * from sysuser where enabled = 1" ); |
或者你可以在 XXMapper.java 接口中定義如下方法:
1
|
List<Map> executeSql(String sql); |
然后使用接口調(diào)用方法:
1
|
xxMapper.executeSql( "select * from sysuser where enabled = 1" ); |
上面這些內(nèi)容可能都會,下面在此基礎(chǔ)上再復(fù)雜一點。
假如像上面SQL中的enabled = 1我想使用參數(shù)方式傳值,也就是寫成 enabled = #{enabled},如果你沒有遇到過類似這種需求,可能不明白為什么要這么寫,舉個例子,要實現(xiàn)一種動態(tài)查詢,可以在前臺通過配置 SQL,提供一些查詢條件就能實現(xiàn)一個查詢的功能(為了安全,這些配置肯定是開發(fā)或者實施做的,不可能讓用戶直接操作數(shù)據(jù)庫)。
針對這個功能,使用 MyBatis 實現(xiàn)起來相當(dāng)容易。配置 SQL 肯定要執(zhí)行,用上面講的這種方式肯定可以執(zhí)行 SQL,如何提供參數(shù)呢?參數(shù)就是enabled = #{enabled}中的#{enabled}部分。如果再多一些條件,一個配置好的 SQL 如下:
1
2
3
|
select * from sysuser where enabled = #{enabled} and userName like concat( '%' ,#{userName}, '%' ) |
這種情況下,該怎么用 MyBatis 實現(xiàn)呢?
首先 XML 中修改如下:
1
2
3
|
< select id= "executeSql" resultType= "map" > ${sql} </ select > |
接口中的方法修改為:
1
|
List<Map> executeSql(Map map); |
然后調(diào)用方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
Map map = new HashMap(); //這里的 sql 對應(yīng) XML 中的 ${sql} map.put( "sql" , "select * from sysuser " + " where enabled = #{enabled} " + " and userName like concat('%',#{userName},'%')" ); //#{enabled} map.put( "enabled" , 1); //#{userName} map.put( "userName" , "admin" ); //接口方式調(diào)用 List<Map> list = xxMapper.executeSql(map); //sqlSession方式調(diào)用 sqlSession.selectList( "executeSql" , map); |
有了這個SQL之后,就可以將 enabled 和 userName 作為條件提供給用戶。這兩個條件顯然是必填的。如果是可選的,那該怎么寫?
也許有人想到了是不是可以用 MyBatis 中的動態(tài) SQL,使用<if>標(biāo)簽等等?
再回答這個問題前,我們先看處理動態(tài) SQL 的 DynamicSqlSource 中的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Override public BoundSql getBoundSql(Object parameterObject) { DynamicContext context = new DynamicContext(configuration, parameterObject); rootSqlNode.apply(context); SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration); Class < ?>parameterType = parameterObject == null ? Object. class : parameterObject.getClass(); SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings()); BoundSql boundSql = sqlSource.getBoundSql(parameterObject); for (Map.Entry < String, Object > entry: context.getBindings().entrySet()) { boundSql.setAdditionalParameter(entry.getKey(), entry.getValue()); } return boundSql; } |
MyBatis 處理動態(tài) SQL 時,所有動態(tài) SQL 的標(biāo)簽都會處理為 SqlNode (這里的rootSqlNode)對象,包含${}的也會處理為 TextSqlNode 對象,在上面方法的前兩行,就是 MyBatis 處理動態(tài) SQL 的地方。
因此如果我們在${sql} 中的內(nèi)容包含嵌套的${}和<if>,<where>等標(biāo)簽時,他們在 MyBatis 解析 XML 為 SqlNode 對象時,XML <select> 元素包含的內(nèi)容只有${sql},只有${sql}會被解析,在運行時這個參數(shù)字符串中可能包含的${}和<if>,<where>等標(biāo)簽,但是這都發(fā)生在 MyBatis 解析后,因此當(dāng)這些內(nèi)容作為字符串中的一部分出現(xiàn)時,他們不會被特殊處理,他們只是SQL中的一部分,只是原樣輸出(由于數(shù)據(jù)庫不認會報錯)無法被處理,因此沒法通過 MyBatis 自帶的這種方式來寫動態(tài) SQL。
提示
在上面的代碼中:
1
|
sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings()); |
這一段代碼是處理動態(tài)參數(shù)(#{})的這個處理在動態(tài) SQL 處理之后, 因此可以在 SQL 中使用這種類型的參數(shù)。
既然不能用 MyBatis 動態(tài) SQL 方式,該怎么實現(xiàn)動態(tài) SQL 呢?
這里提供一個簡單的思路,在 SQL 中使用模板標(biāo)記語言來實現(xiàn)動態(tài)SQL(例如freemarker),在 SQL 交給 MyBatis 執(zhí)行之前,使用模板對 SQL 進行處理生成最終執(zhí)行的 SQL(需要避免處理#{}參數(shù)),將這個SQL交給 MyBatis 執(zhí)行。
舉一個Freemarker模板的例子,仍然以上面的SQL為基礎(chǔ):
1
2
3
4
5
6
7
8
|
select * from sysuser where 1 = 1 <# if enabled??> enabled = #{enabled} </# if > <# if userName?? && userName != '' > and userName like concat( '%' ,#{userName}, '%' ) </# if > |
注意,這里的<#if>是Freemarker的元素。在不考慮SQL注入的情況下,上面的SQL還可以寫成:
1
2
3
4
5
6
7
8
|
select * from sysuser where 1 = 1 <# if enabled??> enabled = #{enabled} </# if > <# if userName?? && userName != '' > and userName like '%${userName}%' </# if > |
區(qū)別就是'%${userName}%',因為 Freemarker 也會處理 ${userName},也會用實際的值來替換這里的參數(shù)。
在前面調(diào)用的代碼中,這里修改如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
//#{enabled} map.put( "enabled" , 1 ); //#{userName} map.put( "userName" , "admin" ); //這里的 sql 對應(yīng) XML 中的 ${sql} String sql = "上面兩個復(fù)雜SQL中的一個" ; //使用Freemarker處理sql sql = processSqlByFreemarker(sql, map); //將處理后的sql放到map中 map.put( "sql" , "select * from sysuser " + " where enabled = #{enabled} " + " and userName like concat('%',#{userName},'%')" ); //執(zhí)行方法 List<Map> list = xxMapper.executeSql(map); |
注:processSqlByFreemarker方法就是根據(jù)map中的數(shù)據(jù)來處理sql字符串,實現(xiàn)方式可以自己搜索。
到這里,一個不是很復(fù)雜的動態(tài)SQL功能就實現(xiàn)了。
不知道有沒有更貪心的人,你會不會想,上面返回值都是List<Map>類型,能不能返回一個我指定的實體類呢?
例如在map中:
1
|
map.put( "class" , "tk.mybatis.model.SysUser" ); |
能不能通過這種方式讓返回值變成SysUser類型呢?由于這篇文章耗時已經(jīng)太長,這里就提供一個方案,不深入。
你可以使用攔截器實現(xiàn),獲取 MappedStatement 后,復(fù)制一份,然后修改 resultMaps中resultMap的type屬性為你指定的class類型就能實現(xiàn),說起來容易,實際操作起來能有 PageHelper 分頁插件 1/10 左右的工作量。
因為這篇是應(yīng)媳婦要求所寫,所以假如媳婦有最后的這個需求,我就協(xié)助媳婦實現(xiàn)這個插件,然后再共享出來。
注:如果是動態(tài)的update,insert,delete 語句,可以將上面的<select>改為update(不需要使用<delete>和<insert>),返回值用int,比 select 的情況容易很多。
以上所述是小編給大家介紹的MyBatis 執(zhí)行動態(tài) SQL語句詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!