Mybatis的 等標簽詳解


sql語句where條件中,需要一些安全判斷,例如按性別檢索,如果傳入的參數是空的,此時查詢出的結果很可能是空的,也許我們需要參數為空 時,是查出全部的信息。這是我們可以使用動態sql,增加一個判斷,當參數不符合要求的時候,我們可以不去判斷此查詢條件。
 下文均采用mysql語法和函數(例如字符串鏈接函數CONCAT

3.1 if標簽
 一個很普通的查詢:

Xml代碼  

 

[html]  view plain  copy
 
  1. <!-- 查詢學生list,like姓名 -->     
  2. <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST       
  4. WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  5. </select>     



 

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

修改為:

Xml代碼  

[html]  view plain  copy
 
  1. <!-- 查詢學生list,like姓名 -->     
  2. <select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <if test="studentName!=null and studentName!='' ">     
  5.         WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  6.     </if>     
  7. </select>     




 此時,當studentName的值為null或’’的時候,我們並不進行where條件的判斷,所以當studentName值為null或’’值,不附帶這個條件,所以查詢結果是全部。

 

 由於參數是Java的實體類,所以我們可以把所有條件都附加上,使用時比較靈活, new一個這樣的實體類,我們需要限制那個條件,只需要附上相應的值就會where這個條件,相反不去賦值就可以不在where中判斷。


   代碼中的where標簽,請參考3.2.1.

Xml代碼  

[html]  view plain  copy
 
  1. <!-- 查詢學生list,like姓名,=性別、=生日、=班級,使用where,參數entity類型 -->     
  2. <select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <where>     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11.         <if test="studentBirthday!=null">     
  12.             AND ST.STUDENT_BIRTHDAY = #{studentBirthday}      
  13.         </if>     
  14.         <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">     
  15.             AND ST.CLASS_ID = #{classEntity.classID}      
  16.         </if>     
  17.     </where>     
  18. </select>     




查詢,姓名中有‘李’,男,生日在‘1985-05-28’,班級在‘20000002’的學生。

 

Java代碼  

[java]  view plain  copy
 
  1. StudentEntity entity = new StudentEntity();      
  2. entity.setStudentName("李");      
  3. entity.setStudentSex("男");      
  4. entity.setStudentBirthday(StringUtil.parse("1985-05-28"));      
  5. entity.setClassEntity(classMapper.getClassByID("20000002"));      
  6. List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity);      
  7. for( StudentEntity entityTemp : studentList){      
  8.     System.out.println(entityTemp.toString());      
  9. }     



 

 

3.2 where、set、trim標簽

3.2.1 where
當if標簽較多時,這樣的組合可能會導致錯誤。例如,like姓名,等於指定性別等:

Xml代碼  

[html]  view plain  copy
 
  1. <!-- 查詢學生list,like姓名,=性別 -->     
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.         WHERE      
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11. </select>     




 如果上面例子,參數studentName為null或’’,則或導致此sql組合成“WHERE AND”之類的關鍵字多余的錯誤SQL。
 這時我們可以使用where動態語句來解決。這個“where”標簽會知道如果它包含的標簽中有返回值的話,它就插入一個‘where’。此外,如果標簽返回的內容是以AND 或OR 開頭的,則它會剔除掉。
 上面例子修改為:

 

Xml代碼  

[html]  view plain  copy
 
  1. <!-- 查詢學生list,like姓名,=性別 -->     
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <where>     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11.     </where>     
  12. </select>     



 

3.2.2 set
當在update語句中使用if標簽時,如果前面的if沒有執行,則或導致逗號多余錯誤。使用set標簽可以將動態的配置SET 關鍵字,和剔除追加到條件末尾的任何不相關的逗號。
沒有使用if標簽時,如果有一個參數為null,都會導致錯誤,如下示例:

Xml代碼  

[html]  view plain  copy
 
  1. <!-- 更新學生信息 -->     
  2. <update id="updateStudent" parameterType="StudentEntity">     
  3.     UPDATE STUDENT_TBL      
  4.        SET STUDENT_TBL.STUDENT_NAME = #{studentName},      
  5.            STUDENT_TBL.STUDENT_SEX = #{studentSex},      
  6.            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
  7.            STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
  8.      WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
  9. </update>     



 

 使用set+if標簽修改后,如果某項為null則不進行更新,而是保持數據庫原值。如下示例:

Xml代碼  

[html]  view plain  copy
 
  1. <!-- 更新學生信息 -->     
  2. <update id="updateStudent" parameterType="StudentEntity">     
  3.     UPDATE STUDENT_TBL      
  4.     <set>     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},      
  7.         </if>     
  8.         <if test="studentSex!=null and studentSex!='' ">     
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},      
  10.         </if>     
  11.         <if test="studentBirthday!=null ">     
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
  13.         </if>     
  14.         <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
  15.             STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
  16.         </if>     
  17.     </set>     
  18.     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
  19. </update>     



3.2.3 trim
 trim是更靈活的去處多余關鍵字的標簽,他可以實踐where和set的效果。

 


 where例子的等效trim語句:

Xml代碼  

[html]  view plain  copy
 
  1. <!-- 查詢學生list,like姓名,=性別 -->     
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <trim prefix="WHERE" prefixOverrides="AND|OR">     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11.     </trim>     
  12. </select>     



set例子的等效trim語句:

 

Xml代碼  

[html]  view plain  copy
 
  1. <!-- 更新學生信息 -->     
  2. <update id="updateStudent" parameterType="StudentEntity">     
  3.     UPDATE STUDENT_TBL      
  4.     <trim prefix="SET" suffixOverrides=",">     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},      
  7.         </if>     
  8.         <if test="studentSex!=null and studentSex!='' ">     
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},      
  10.         </if>     
  11.         <if test="studentBirthday!=null ">     
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
  13.         </if>     
  14.         <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
  15.             STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
  16.         </if>     
  17.     </trim>     
  18.     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
  19. </update>     



 

3.3 choose (when, otherwise)
         有時候我們並不想應用所有的條件,而只是想從多個選項中選擇一個。MyBatis提供了choose 元素,按順序判斷when中的條件出否成立,如果有一個成立,則choose結束。當choose中所有when的條件都不滿則時,則執行 otherwise中的sql。類似於Java 的switch 語句,choose為switch,when為case,otherwise則為default。
         if是與(and)的關系,而choose是或(or)的關系。


         例如下面例子,同樣把所有可以限制的條件都寫上,方面使用。選擇條件順序,when標簽的從上到下的書寫順序:

Xml代碼  

[html]  view plain  copy
 
  1. <!-- 查詢學生list,like姓名、或=性別、或=生日、或=班級,使用choose -->     
  2. <select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <where>     
  5.         <choose>     
  6.             <when test="studentName!=null and studentName!='' ">     
  7.                     ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  8.             </when>     
  9.             <when test="studentSex!= null and studentSex!= '' ">     
  10.                     AND ST.STUDENT_SEX = #{studentSex}      
  11.             </when>     
  12.             <when test="studentBirthday!=null">     
  13.                 AND ST.STUDENT_BIRTHDAY = #{studentBirthday}      
  14.             </when>     
  15.             <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">     
  16.                 AND ST.CLASS_ID = #{classEntity.classID}      
  17.             </when>     
  18.             <otherwise>     
  19.                       
  20.             </otherwise>     
  21.         </choose>     
  22.     </where>     
  23. </select>     



3.4 foreach
對於動態SQL 非常必須的,主是要迭代一個集合,通常是用於IN 條件。
List 實例將使用“list”做為鍵,數組實例以“array” 做為鍵。

 

 

 3.4.1參數為list實例的寫法:
SQL寫法:

Xml代碼  

[html]  view plain  copy
 
  1. <select id="getStudentListByClassIDs" resultMap="studentResultMap">     
  2.     SELECT * FROM STUDENT_TBL ST      
  3.      WHERE ST.CLASS_ID IN       
  4.      <foreach collection="list" item="classList"  open="(" separator="," close=")">     
  5.         #{classList}      
  6.      </foreach>         
  7. </select>     



接口的方法聲明:

 

 

[java]  view plain  copy
 
  1. public List<StudentEntity> getStudentListByClassIDs(List<String> classList);     
  2. public List<StudentEntity> getStudentListByClassIDs(List<String> classList); 測試代碼,查詢學生中,在20000002、20000003這兩個班級的學生:  

 

 

 

[java]  view plain  copy
 
  1. List<String> classList = new ArrayList<String>();      
  2. classList.add("20000002");      
  3. classList.add("20000003");      
  4.      
  5. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList);      
  6. for( StudentEntity entityTemp : studentList){      
  7.     System.out.println(entityTemp.toString());      
  8. }     
  9. List<String> classList = new ArrayList<String>();  
  10. classList.add("20000002");  
  11. classList.add("20000003");  
  12. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList);  
  13. for( StudentEntity entityTemp : studentList){  
  14.  System.out.println(entityTemp.toString());  
  15. }  

 

 

 3.4.2參數為Array實例的寫法:
SQL語句:

 

[html]  view plain  copy
 
  1. <select id="getStudentListByClassIDs" resultMap="studentResultMap">     
  2.     SELECT * FROM STUDENT_TBL ST      
  3.      WHERE ST.CLASS_ID IN       
  4.      <foreach collection="array" item="ids"  open="(" separator="," close=")">     
  5.         #{ids}      
  6.      </foreach>     
  7. </select>     



 

 接口的方法聲明:

 

[java]  view plain  copy
 
  1. public List<StudentEntity> getStudentListByClassIDs(String[] ids);     
  2. public List<StudentEntity> getStudentListByClassIDs(String[] ids);測試代碼,查詢學生中,在20000002、20000003這兩個班級的學生:  

 

 

[java]  view plain  copy
 
    1. String[] ids = new String[2];      
    2. ids[0] = "20000002";      
    3. ids[1] = "20000003";      
    4. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(ids);      
    5. for( StudentEntity entityTemp : studentList){      
    6.     System.out.println(entityTemp.toString());      
    7. }   


免責聲明!

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



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