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