MyBatis的動態SQL


MyBatis的動態SQL是基於OGNL表達式的,它可以幫助我們方便的在SQL語句中實現某些邏輯。

MyBatis中用於實現動態SQL的元素主要有:

 

  • if
  • choose(when,otherwise)
  • trim
  • where
  • set
  • foreach
if就是簡單的條件判斷,利用if語句我們可以實現某些簡單的條件選擇。先來看如下一個例子:
<select id="findAllInfosCount" resultType="int">
        select count(*) from student where 1=1
        <if test="name != null and name != ''"> and NAME like CONCAT('%','${name}','%')</if>
        <if test="gender != null and gender != ''"> and GENDER = #{gender}</if>
        <if test="course != null and course != ''"> and COURSE = #{course}</if>
        <if test="examdate != null and examdate != ''"> and EXAMDATE between #{examdate}</if>
    </select>
    
    <select id="findAllInfos" parameterType="com.cib.yypt.sample.vo.StudentVO" resultMap="studentMap">
        select STUDENTZJ,STUDENTID,NAME,GENDER,COURSE,SCORE,EXAMDATE from student where 1=1
        <if test="name != null and name != ''"> and NAME like CONCAT('%','${name}','%')</if>
        <if test="gender != null and gender != ''"> and GENDER = #{gender}</if>
        <if test="course != null and course != ''"> and COURSE = #{course}</if>
        <if test="examdate != null and examdate != ''"> and EXAMDATE between #{examdate}</if>
    </select>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cib.studentmanagement.dao.IStudentDao">
    <resultMap id="khxxCxMap" type="com.cib.studentmanagement.vo.StudentVO">
        <id column="STUDENTZJ" property="studentzj" />
        <result column="STUDENTID" property="studentid" />
        <result column="NAME" property="name" />
        <result column="GENDER" property="gender" />
        <result column="COURSE" property="course" />
        <result column="SCORE" property="score" />
        <result column="EXAMDATE" property="examdate" />
    </resultMap>

    <select id="findAllInfosCount" resultType="int">
        select count(*)
        from student
        where 1=1
        <if test="studentid != null and studentid != ''"> and STUDENTID = #{studentid}</if>
        <if test="name != null and name != ''"> and NAME like ${name}</if>
        <if test="gender != null and gender != ''"> and GENDER = #{gender}</if>
        <if test="course != null and course != ''"> and COURSE = #{course}</if>
        <if test="score_min != null and score_min != ''"> and SCORE >= #{score_min}</if>
        <if test="score_max != null and score_max != ''"> and SCORE <![CDATA[<=]]> #{score_max}</if>  
        <if test="examdate != null and examdate != ''"> and EXAMDATE = #{examdate}</if>
    </select>

    <select id="findAllInfos" parameterType="com.cib.studentmanagement.vo.StudentVO"
        resultMap="studentMap">
        select STUDENTZJ,STUDENTID,NAME,GENDER,COURSE,SCORE,EXAMDATE
        from student
        where 1=1
        <if test="studentid != null and studentid != ''"> and STUDENTID = #{studentid}</if>
        <if test="name != null and name != ''"> and NAME like ${name}</if>
        <if test="gender != null and gender != ''"> and GENDER = #{gender}</if>
        <if test="course != null and course != ''"> and COURSE = #{course}</if>
        <if test="score_min != null and score_min != ''"> and SCORE >= #{score_min}</if>
        <if test="score_max != null and score_max != ''"> and SCORE <![CDATA[<=]]> #{score_max}</if>
        <if test="examdate != null and examdate != ''"> and EXAMDATE = #{examdate}</if>
    </select>

    <insert id="save" parameterType="com.cib.studentmanagement.vo.StudentVO">
        INSERT INTO student
        (STUDENTZJ,STUDENTID,NAME,GENDER,COURSE,SCORE,EXAMDATE)
        values
        (#{studentzj,jdbcType=CHAR},#{studentid,jdbcType=CHAR},#{name,jdbcType=VARCHAR},#{gender,jdbcType=CHAR},
            #{course,jdbcType=VARCHAR},#{score,jdbcType=DOUBLE},#{examdate,jdbcType=TIMESTAMP})
</insert> <update id="update" parameterType="com.cib.studentmanagement.vo.StudentVO"> update student <trim prefix="SET" suffixOverrides=","> <if test="studentzj != null"> STUDENTZJ = #{studentzj},</if> <if test="studentid != null"> STUDENTID = #{studentid},</if> <if test="name != null"> NAME = #{name},</if> <if test="gender != null"> GENDER = #{gender},</if> <if test="course != null"> COURSE = #{course},</if> <if test="score != null"> SCORE = #{score},</if> <if test="examdate != null"> EXAMDATE = #{examdate},</if> </trim> where <trim prefix="" suffixOverrides="AND"> <if test="studentzj != null">STUDENTZJ = #{studentzj} AND </if> </trim> </update> <delete id="delete" parameterType="com.cib.studentmanagement.vo.StudentVO"> delete from student <trim prefix="WHERE" prefixOverrides="AND"> <if test="studentzj != null"> AND STUDENTZJ = #{studentzj}</if> </trim> </delete> </mapper>

choose元素的作用就相當於JAVA中的switch語句,基本上跟JSTL中的choose的作用和用法是一樣的,通常都是與when和otherwise搭配的。看如下一個例子:

    <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>  

where語句的作用主要是簡化SQL語句中where中的條件判斷的,先看一個例子,再解釋一下where的好處。

    <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 給忽略。

 
trim元素的主要功能是可以在自己包含的內容前加上某些前綴,也可以在其后加上某些后綴,與之對應的屬性是 prefix和suffix;可以把包含內容的首部某些內容覆蓋,即忽略,也可以把尾部的某些內容覆蓋,對應的屬性是prefixOverrides和 suffixOverrides;正因為trim有這樣的功能,所以我們也可以非常簡單的利用trim來代替where元素的功能,示例代碼如下:
    <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>  

set元素主要是用在更新操作的時候,它的主要功能和where元素其實是差不多的,主要是在包含的語句前輸出一個 set,然后如果包含的語句是以逗號結束的話將會把該逗號忽略,如果set包含的內容為空的話則會出錯。有了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中一個條件都不滿足,即set中包含的內容為空的時候就會報錯。
 
foreach的主要用在構建in條件中,它可以在SQL語句中進行迭代一個集合。foreach元素的屬性主要有 item,index,collection,open,separator,close。item表示集合中每一個元素進行迭代時的別名,index指 定一個名字,用於表示在迭代過程中,每次迭代到的位置,open表示該語句以什么開始,separator表示在每次進行迭代之間以什么符號作為分隔 符,close表示以什么結束,在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,但是在不同情況 下,該屬性的值是不一樣的,主要有一下3種情況:
  1. 如果傳入的是單參數且參數類型是一個List的時候,collection屬性值為list
  2. 如果傳入的是單參數且參數類型是一個array數組的時候,collection的屬性值為array
  3. 如果傳入的參數是多個的時候,我們就需要把它們封裝成一個Map了,當然單參數也可以封裝成map,實際上如果你在傳入參數的時候,在MyBatis里面也是會把它封裝成一個Map的,map的key就是參數名,所以這個時候collection屬性值就是傳入的List或array對象在自己封裝的map里面的key
下面分別來看看上述三種情況的示例代碼:
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();  
    }  

2.單參數array數組的類型:

    <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>  

上述collection為array,對應的Mapper代碼:

    public List<Blog> dynamicForeach2Test(int[] ids);  

 對應的測試代碼:

    @Test  
    public void dynamicForeach2Test() {  
        SqlSession session = Util.getSqlSessionFactory().openSession();  
        BlogMapper blogMapper = session.getMapper(BlogMapper.class);  
        int[] ids = new int[] {1,3,6,9};  
        List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);  
        for (Blog blog : blogs)  
            System.out.println(blog);  
        session.close();  
    }  

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>  

上述collection的值為ids,是傳入的參數Map的key,對應的Mapper代碼:

public List<Blog> dynamicForeach3Test(Map<String, Object> params); 

對應測試代碼:

    @Test  
    public void dynamicForeach3Test() {  
        SqlSession session = Util.getSqlSessionFactory().openSession();  
        BlogMapper blogMapper = session.getMapper(BlogMapper.class);  
        final List<Integer> ids = new ArrayList<Integer>();  
        ids.add(1);  
        ids.add(2);  
        ids.add(3);  
        ids.add(6);  
        ids.add(7);  
        ids.add(9);  
        Map<String, Object> params = new HashMap<String, Object>();  
        params.put("ids", ids);  
        params.put("title", "中國");  
        List<Blog> blogs = blogMapper.dynamicForeach3Test(params);  
        for (Blog blog : blogs)  
            System.out.println(blog);  
        session.close();  
    }  

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM