天天看點

MyBatis - 動态SQL

MyBatis的動态SQL是基于OGNL表達式的,它可以幫助我們友善的在SQL語句中實作某些邏輯。 

MyBatis中用于實作動态SQL的元素主要有

  • if
  • where
  • set
  • choose(when,otherwise)
  • trim
  • foreach

1、if 标簽

if标簽可用在許多類型的sql語句中,我們以查詢為例。首先看一個很普通的查詢

<!-- 查詢學生list,like姓名 -->  
<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  
    SELECT * from STUDENT_TBL ST   
    WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
</select>      

但是此時如果studentName為null,此語句很可能報錯或查詢結果為空。此時我們使用if動态sql語句先進行判斷,如果值為null或等于空字元串,我們就不進行此條件的判斷,增加靈活性。 

參數為實體類StudentEntity。将實體類中所有的屬性均進行判斷,如果不為空則執行判斷條件。

<!-- 2 if(判斷參數) - 将實體類不為空的屬性作為where條件 -->  
<select id="getStudentList_if" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
    SELECT ST.STUDENT_ID,  
           ST.STUDENT_NAME,  
           ST.STUDENT_SEX,  
           ST.STUDENT_BIRTHDAY,  
           ST.STUDENT_PHOTO,  
           ST.CLASS_ID,  
           ST.PLACE_ID  
    FROM STUDENT_TBL ST   
    WHERE  
    <if test="studentName !=null ">  
        ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
    </if>  
    <if test="studentSex != null and studentSex != '' ">  
        AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
    </if>  
    <if test="studentBirthday != null ">  
        AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
    </if>  
    <if test="classId != null and classId!= '' ">  
        AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
    </if>  
    <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !='' ">  
        AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
    </if>  
    <if test="placeId != null and placeId != '' ">  
        AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
    </if>  
    <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
        AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
    </if>  
    <if test="studentId != null and studentId != '' ">  
        AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
    </if>   
</select>      

使用時比較靈活, new一個這樣的實體類,我們需要限制那個條件,隻需要附上相應的值就會where這個條件,相反不去指派就可以不在where中判斷。

public void select_test_2_1() {  
    StudentEntity entity = new StudentEntity();  
    entity.setStudentName("");  
    entity.setStudentSex(1);  
    entity.setStudentBirthday(DateUtil.parse("1985-05-28"));  
    entity.setClassId("20000001");  
    //entity.setPlaceId("70000001");  
    List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);  
    for (StudentEntity e : list) {  
        System.out.println(e.toString());  
    }  
}      

2、if + where 的條件判斷

當where中的條件使用的if标簽較多時,這樣的組合可能會導緻錯誤。我們以在1中的查詢語句為例子,當java代碼按如下方法調用時

@Test  
public void select_test_2_1() {  
    StudentEntity entity = new StudentEntity();  
    entity.setStudentName(null);  
    entity.setStudentSex(1);  
    List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);  
    for (StudentEntity e : list) {  
        System.out.println(e.toString());  
    }  
}      

如果上面例子,參數studentName為null,将不會進行STUDENT_NAME列的判斷,則會直接導“WHERE AND”關鍵字多餘的錯誤SQL。

這時我們可以使用where動态語句來解決。這個“where”标簽會知道如果它包含的标簽中有傳回值的話,它就插入一個‘where’。此外,如果标簽傳回的内容是以AND 或OR 開頭的,則它會剔除掉。 

上面例子修改為

<!-- 3 select - where/if(判斷參數) - 将實體類不為空的屬性作為where條件 -->  
<select id="getStudentList_whereIf" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
    SELECT ST.STUDENT_ID,  
           ST.STUDENT_NAME,  
           ST.STUDENT_SEX,  
           ST.STUDENT_BIRTHDAY,  
           ST.STUDENT_PHOTO,  
           ST.CLASS_ID,  
           ST.PLACE_ID  
      FROM STUDENT_TBL ST   
    <where>  
        <if test="studentName !=null ">  
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
        </if>  
        <if test="studentSex != null and studentSex != '' ">  
            AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
        </if>  
        <if test="studentBirthday != null ">  
            AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
        </if>  
        <if test="classId != null and classId!= '' ">  
            AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
        </if>  
        <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
            AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeId != null and placeId != '' ">  
            AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
            AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="studentId != null and studentId != '' ">  
            AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
        </if>  
    </where>    
</select>      

3、if + set 的更新語句

當update語句中沒有使用if标簽時,如果有一個參數為null,都會導緻錯誤。 

當在update語句中使用if标簽時,如果前面的if沒有執行,則或導緻逗号多餘錯誤。使用set标簽可以将動态的配置SET 關鍵字,和剔除追加到條件末尾的任何不相關的逗号。如果set包含的内容為空的話則會出錯。

使用if+set标簽修改後,如果某項為null則不進行更新,而是保持資料庫原值。如下示例

<!-- 4 if/set(判斷參數) - 将實體類不為空的屬性更新 -->  
<update id="updateStudent_if_set" parameterType="liming.student.manager.data.model.StudentEntity">  
    UPDATE STUDENT_TBL  
    <set>  
        <if test="studentName != null and studentName != '' ">  
            STUDENT_TBL.STUDENT_NAME = #{studentName},  
        </if>  
        <if test="studentSex != null and studentSex != '' ">  
            STUDENT_TBL.STUDENT_SEX = #{studentSex},  
        </if>  
        <if test="studentBirthday != null ">  
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
        </if>  
        <if test="studentPhoto != null ">  
            STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
        </if>  
        <if test="classId != '' ">  
            STUDENT_TBL.CLASS_ID = #{classId}  
        </if>  
        <if test="placeId != '' ">  
            STUDENT_TBL.PLACE_ID = #{placeId}  
        </if>  
    </set>  
    WHERE STUDENT_TBL.STUDENT_ID = #{studentId};      
</update>      

4、choose (when, otherwise)

有時候我們并不想應用所有的條件,而隻是想從多個選項中選擇一個。而使用if标簽時,隻要test中的表達式為true,就會執行if标簽中的條件。MyBatis提供了choose 元素。if标簽是與(and)的關系,而choose标簽是或(or)的關系。

choose标簽是按順序判斷其内部when标簽中的test條件出否成立,如果有一個成立,則choose結束。當choose中所有when的條件都不滿則時,則執行otherwise中的sql。類似于Java 的switch 語句,choose為switch,when為case,otherwise則為default。

例如下面例子,同樣把所有可以限制的條件都寫上,方面使用。choose會從上到下選擇一個when标簽的test為true的sql執行。安全考慮,我們使用where将choose包起來,放置關鍵字多于錯誤。

<!-- 6 choose(判斷參數) - 按順序将實體類第一個不為空的屬性作為where條件 -->  
<select id="getStudentList_choose" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
    SELECT ST.STUDENT_ID,  
           ST.STUDENT_NAME,  
           ST.STUDENT_SEX,  
           ST.STUDENT_BIRTHDAY,  
           ST.STUDENT_PHOTO,  
           ST.CLASS_ID,  
           ST.PLACE_ID  
      FROM STUDENT_TBL ST   
    <where>  
        <choose>  
            <when test="studentName !=null ">  
                ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
            </when >  
            <when test="studentSex != null and studentSex != '' ">  
                AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
            </when >  
            <when test="studentBirthday != null ">  
                AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
            </when >  
            <when test="classId != null and classId!= '' ">  
                AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
            </when >  
            <when test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
                AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
            </when >  
            <when test="placeId != null and placeId != '' ">  
                AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
            </when >  
            <when test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
                AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
            </when >  
            <when test="studentId != null and studentId != '' ">  
                AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
            </when >  
            <otherwise>  
            </otherwise>  
        </choose>  
    </where>    
</select>      

5、trim标簽

trim元素的主要功能是可以在自己包含的内容前加上某些字首,也可以在其後加上某些字尾,與之對應的屬性是prefix和suffix;可以把包含内容的首部某些内容覆寫,即忽略,也可以把尾部的某些内容覆寫,對應的屬性是prefixOverrides和suffixOverrides。正因為trim有這樣的功能,是以我們也可以非常簡單的利用trim來代替where/set标簽的功能,示例代碼如下

trim代替where标簽

<!-- 5.1 if/trim代替where(判斷參數) - 将實體類不為空的屬性作為where條件 -->  
<select id="getStudentList_if_trim" resultMap="resultMap_studentEntity">  
    SELECT ST.STUDENT_ID,  
           ST.STUDENT_NAME,  
           ST.STUDENT_SEX,  
           ST.STUDENT_BIRTHDAY,  
           ST.STUDENT_PHOTO,  
           ST.CLASS_ID,  
           ST.PLACE_ID  
      FROM STUDENT_TBL ST   
    <trim prefix="WHERE" prefixOverrides="AND|OR">  
        <if test="studentName !=null ">  
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
        </if>  
        <if test="studentSex != null and studentSex != '' ">  
            AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
        </if>  
        <if test="studentBirthday != null ">  
            AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
        </if>  
        <if test="classId != null and classId!= '' ">  
            AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
        </if>  
        <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
            AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeId != null and placeId != '' ">  
            AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
            AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="studentId != null and studentId != '' ">  
            AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
        </if>  
    </trim>     
</select>      

trim代替set标簽

<!-- 5.2 if/trim代替set(判斷參數) - 将實體類不為空的屬性更新 -->  
<update id="updateStudent_if_trim" parameterType="liming.student.manager.data.model.StudentEntity">  
    UPDATE STUDENT_TBL  
    <trim prefix="SET" suffixOverrides=",">  
        <if test="studentName != null and studentName != '' ">  
            STUDENT_TBL.STUDENT_NAME = #{studentName},  
        </if>  
        <if test="studentSex != null and studentSex != '' ">  
            STUDENT_TBL.STUDENT_SEX = #{studentSex},  
        </if>  
        <if test="studentBirthday != null ">  
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
        </if>  
        <if test="studentPhoto != null ">  
            STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
        </if>  
        <if test="classId != '' ">  
            STUDENT_TBL.CLASS_ID = #{classId},  
        </if>  
        <if test="placeId != '' ">  
            STUDENT_TBL.PLACE_ID = #{placeId}  
        </if>  
    </trim>  
    WHERE STUDENT_TBL.STUDENT_ID = #{studentId}  
</update>      

6、foreach标簽

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

下面分别來看看上述三種情況的示例代碼

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();  
}      
<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>      
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();  
}      

繼續閱讀