mybatis 動態sql
名詞解析
OGNL表達式
OGNL,全稱為Object-Graph Navigation Language,它是一個功能強大的表達式語言,用來獲取和設置Java對象的屬性,它旨在提供一個更高的更抽象的層次來對Java對象圖進行導航。
OGNL表達式的基本單位是"導航鏈",一般導航鏈由如下幾個部分組成:
- 屬性名稱(property)
- 方法調用(method invoke)
- 數組元素
所有的OGNL表達式都基於當前對象的上下文來完成求值運算,鏈的前面部分的結果將作為后面求值的上下文。例如:names[0].length()。
mybatis 的動態sql語句是基於OGNL表達式的。可以方便的在 sql 語句中實現某些邏輯. 總體說來mybatis 動態SQL 語句主要有以下幾類:
1. if 語句 (簡單的條件判斷)
2. choose (when,otherwize) ,相當於java 語言中的 switch ,與 jstl 中的choose 很類似.
3. trim (對包含的內容加上 prefix,或者 suffix 等,前綴,后綴)
4. where (主要是用來簡化sql語句中where條件判斷的,能智能的處理 and or ,不必擔心多余導致語法錯誤)
5. set (主要用於更新時)
6. foreach (在實現 mybatis in 語句查詢時特別有用)
下面分別介紹這幾種處理方式
1. mybaits if 語句處理
<select id="dynamicIfTest" parameterType="Blog" resultType="Blog"> select * from t_blog where 1 = 1 <if test="title != null"> and title = #{title} </if> <if test="content != null"> and content = #{content} </if> <if test="owner != null"> and owner = #{owner} </if> </select>
解析:
如果你提供了title參數,那么就要滿足title=#{title},同樣如果你提供了Content和Owner的時候,它們也需要滿足相應的條件,之后就是返回滿足這些條件的所有Blog,這是非常有用的一個功能。
以往我們使用其他類型框架或者直接使用JDBC的時候, 如果我們要達到同樣的選擇效果的時候,我們就需要拼SQL語句,這是極其麻煩的,比起來,上述的動態SQL就要簡單多了。
2. choose (when,otherwize) ,相當於java 語言中的 switch ,與 jstl 中的choose 很類似
<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog"> select * from t_blog where 1 = 1 <choose> <when test="title != null"> and title = #{title} </when> <when test="content != null"> and content = #{content} </when> <otherwise> and owner = "owner1" </otherwise> </choose> </select>
when元素表示當when中的條件滿足的時候就輸出其中的內容,跟JAVA中的switch效果差不多的是按照條件的順序,當when中有條件滿足的時候,就會跳出choose,即所有的when和otherwise條件中,只有一個會輸出, 當所有的我很條件都不滿足的時候就輸出otherwise中的內容。所以上述語句的意思非常簡單, 當title!=null的時候就輸出and titlte = #{title},不再往下判斷條件,當title為空且content!=null的時候就輸出and content = #{content},當所有條件都不滿足的時候就輸出otherwise中的內容。
3.trim (對包含的內容加上 prefix,或者 suffix 等,前綴,后綴)
<select id="dynamicTrimTest" parameterType="Blog" resultType="Blog"> select * from t_blog <trim prefix="where" prefixOverrides="and |or"> <if test="title != null"> title = #{title} </if> <if test="content != null"> and content = #{content} </if> <if test="owner != null"> or owner = #{owner} </if> </trim> </select>
trim元素的主要功能是可以在自己包含的內容前加上某些前綴,也可以在其后加上某些后綴, 與之對應的屬性是prefix和suffix;可以把包含內容的首部某些內容覆蓋,即忽略,也可以把尾部的某些內容覆蓋,對應的屬性是 prefixOverrides和suffixOverrides;正因為trim有這樣的功能,所以我們也可以非常簡單的利用trim來代替where 元素的功能
4. where (主要是用來簡化sql語句中where條件判斷的,能智能的處理 and or 條件
<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog"> select * from t_blog <where> <if test="title != null"> title = #{title} </if> <if test="content != null"> and content = #{content} </if> <if test="owner != null"> and owner = #{owner} </if> </where> </select>
where元素的作用是會在寫入where元素的地方輸出一個where,另外一個好處是你不需要考慮where元素里面的條件輸出是什么樣子的,MyBatis 會智能的幫你處理,如果所有的條件都不滿足那么MyBatis就會查出所有的記錄,如果輸出后是and 開頭的,MyBatis會把第一個and忽略,當然如果是or開頭的,MyBatis也會把它忽略;此外,在where元素中你不需要考慮空格的問 題,MyBatis會智能的幫你加上。像上述例子中,如果title=null, 而content != null,那么輸出的整個語句會是select * from t_blog where content = #{content},而不是select * from t_blog where and content = #{content},因為MyBatis會智能的把首個and 或 or 給忽略。
5.set (主要用於更新時)
<update id="dynamicSetTest" parameterType="Blog"> update t_blog <set> <if test="title != null"> title = #{title}, </if> <if test="content != null"> content = #{content}, </if> <if test="owner != null"> owner = #{owner} </if> </set> where id = #{id} </update>
set元素主要是用在更新操作的時候,它的主要功能和where元素其實是差不多的,主要是在包含的語句前輸出一個set,然后如果包含的語句是以逗號結束的話將會把該逗號忽略,如果set包含的內容為空的話則會出錯。有了set元素我們就可以動態的更新那些修改了的字段
6. foreach (在實現 mybatis in 語句查詢時特別有用)
foreach的主要用在構建in條件中,它可以在SQL語句中進行迭代一個集合。foreach元素的屬性主要有item,index,collection,open,separator,close。
- item表示集合中每一個元素進行迭代時的別名,
- index指定一個名字,用於表示在迭代過程中,每次迭代到的位置,
- open表示該語句以什么開始,
- separator表示在每次進行迭代之間以什么符號作為分隔符,
- close表示以什么結束,
在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,但是在不同情況下,該屬性的值是不一樣的,主要有一下3種情況:
- 如果傳入的是單參數且參數類型是一個List的時候,collection屬性值為list
- 如果傳入的是單參數且參數類型是一個array數組的時候,collection的屬性值為array
- 如果傳入的參數是多個的 時候,我們就需要把它們封裝成一個Map了,當然單參數也可以封裝成map,實際上如 果你在傳入參數的時候,在MyBatis里面也是會把它封裝成一個Map的,map的key就是參數名,所以這個時候collection屬性值就是傳入 的List或array對象在自己封裝的map里面的key
6.1.單參數List的類型
<select id="dynamicForeachTest" resultType="Blog"> select * from t_blog where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
上述collection的值為list,對應的Mapper是這樣的
public List<Blog> dynamicForeachTest(List<Integer> ids);
測試代碼
@Test
public void dynamicForeachTest() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(3); ids.add(6); List<Blog> blogs = blogMapper.dynamicForeachTest(ids); for (Blog blog : blogs) System.out.println(blog); session.close(); }
6.2.數組類型的參數
<select id="dynamicForeach2Test" resultType="Blog"> select * from t_blog where id in <foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
對應mapper
public List<Blog> dynamicForeach2Test(int[] ids);
6.3. Map 類型的參數
<select id="dynamicForeach3Test" resultType="Blog"> select * from t_blog where title like "%"#{title}"%" and id in <foreach collection="ids" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
mapper 應該是這樣的接口:
public List<Blog> dynamicForeach3Test(Map<String, Object> params);
通過以上方法,就能完成一般的mybatis 的 動態SQL 語句.最常用的就是 if where foreach這幾個,一定要重點掌握.
MyBatis傳入參數與parameterType
Mybatis的Mapper文件中的select、insert、update、delete元素中有一個parameterType屬性,用於對應的mapper接口方法接受的參數類型。
可以接受的參數類型有基本類型和復雜類型。
mapper接口方法一般接受一個參數,可以通過使用@Param注釋將多個參數綁定到一個map做為輸入參數。
- 簡單數據類型
mapper接口方法:
User selectByPrimaryKey(Integer id);
sql映射:
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from base.tb_user where id = #{id,jdbcType=INTEGER} </select>
對於簡單數據類型,sql映射語句中直接#{變量名}這種方式引用就行了,其實這里的”變量名”可以是任意的。mapper接口方法傳遞過來的值,至於其叫什么名字其實是不可考也沒必要知道的。
而且JAVA反射只能獲取方法參數的類型,是無從得知方法參數的名字的。
比如上面這個示例中,使用#{id}來引用只是比較直觀而已,使用其他名字來引用也是一樣的。所以當在if元素中test傳遞的參數時,就必須要用_parameter來引用這個參數了。像這樣:
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from tb_user <if test="_parameter != 0"> where id = #{id,jdbcType=INTEGER} </if> </select>
如果test測試條件中使用id就會提示錯誤,因為這個參數其實沒有名字,只是一個值或引用而已,只能使用_parameter來引用。
- 對象類型
傳入JAVA復雜對象類型的話,sql映射語句中就可以直接引用對象的屬性名了,這里的屬性名是實實在在的真實的名字,不是隨意指定的。
mapper接口方法:
int insert(User user);
sql映射:
<insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into tb_user (name, sex) values (#{name,jdbcType=CHAR}, #{sex,jdbcType=CHAR}) </insert>
雖然可以明確的引用對象的屬性名了,但如果要在if元素中測試傳入的user參數,仍然要使用_parameter來引用傳遞進來的實際參數,因為傳遞進來的User對象的名字是不可考的。如果測試對象的屬性,則直接引用屬性名字就可以了。
測試user對象:
<if test="_parameter != null">
測試user對象的屬性:
<if test="name != null">
- map類型
傳入map類型,直接通過#{keyname}就可以引用到鍵對應的值。使用@param注釋的多個參數值也會組裝成一個map數據結構,和直接傳遞map進來沒有區別。
mapper接口:
int updateByExample(@Param("user") User user, @Param("example") UserExample example);
sql映射:
<update id="updateByExample" parameterType="map" > update tb_user set id = #{user.id,jdbcType=INTEGER}, ... <if test="_parameter != null" > <include refid="Update_By_Example_Where_Clause" /> </if> </update>
注意這里測試傳遞進來的map是否為空,仍然使用_parameter
- 集合類型
You can pass a List instance or an Array to MyBatis as a parameter object. When you do, MyBatis will automatically wrap it in a Map, and key it by name. List instances will be keyed to the name “list” and array instances will be keyed to the name “array”.
可以傳遞一個List或Array類型的對象作為參數,MyBatis會自動的將List或Array對象包裝到一個Map對象中,List類型對象會使用list作為鍵名,而Array對象會用array作為鍵名。
集合類型通常用於構造IN條件,sql映射文件中使用foreach元素來遍歷List或Array元素。
mapper接口:
User selectUserInList(List<Interger> idlist);
sql動態語句映射:
<select id="selectUserInList" resultType="User"> SELECT * FROM USER WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>
- 對象類型中的集合屬性
對於單獨傳遞的List或Array,在SQL映射文件中映射時,只能通過list或array來引用。但是如果對象類型有屬性的類型為List或Array,則在sql映射文件的foreach元素中,可以直接使用屬性名字來引用。
mapper接口:
List<User> selectByExample(UserExample example);
sql映射文件:
<where > <foreach collection="oredCriteria" item="criteria" separator="or" > <if test="criteria.valid" > </where>
在這里,UserExample有一個屬性叫oredCriteria,其類型為List,所以在foreach元素里直接用屬性名oredCriteria引用這個List即可。
item=”criteria”表示使用criteria這個名字引用每一個集合中的每一個List或Array元素