歡迎光臨
每天分享高質量文章

關於Mybaits,我總結了 10 種通用的寫法


用來迴圈容器的標簽forEach,檢視例子

foreach元素的屬性主要有item,index,collection,open,separator,close。

  • item:集合中元素迭代時的別名,
  • index:集合中元素迭代時的索引
  • open:常用語where陳述句中,表示以什麼開始,比如以'(‘開始
  • separator:表示在每次進行迭代時的分隔符,
  • close 常用語where陳述句中,表示以什麼結束,

在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,但是在不同情況下,該屬性的值是不一樣的,主要有一下3種情況:

  • 如果傳入的是單引數且引數型別是一個List的時候,collection屬性值為list .
  • 如果傳入的是單引數且引數型別是一個array陣列的時候,collection的屬性值為array .
  • 如果傳入的引數是多個的時候,我們就需要把它們封裝成一個Map了,當然單引數也可以封裝成map,實際上如果你在傳入引數的時候,在MyBatis裡面也是會把它封裝成一個Map的,map的key就是引數名,所以這個時候collection屬性值就是傳入的List或array物件在自己封裝的map裡面的key.

針對最後一條,我們來看一下官方說法:

註意 你可以將一個 List 實體或者陣列作為引數物件傳給 MyBatis,當你這麼做的時候,MyBatis 會自動將它包裝在一個 Map 中並以名稱為鍵。List 實體將會以“list”作為鍵,而陣列實體的鍵將是“array”。

所以,不管是多引數還是單引數的list,array型別,都可以封裝為map進行傳遞。如果傳遞的是一個List,則mybatis會封裝為一個list為key,list值為object的map,如果是array,則封裝成一個array為key,array的值為object的map,如果自己封裝呢,則colloection裡放的是自己封裝的map裡的key值

  1. //mapper中我們要為這個方法傳遞的是一個容器,將容器中的元素一個一個的
  2. //拼接到xml的方法中就要使用這個forEach這個標簽了
  3. public List queryById(List userids);
  4.  
  5. //對應的xml中如下
  6.    id="queryById" resultMap="BaseReslutMap" >
  7.       select * FROM entity
  8.       where id in 
  9.        collection="userids" item="userid" index="index" open="(" separator="," close=")">
  10.               #{userid}
  11.       
  •   

concat模糊查詢

  1. //比如說我們想要進行條件查詢,但是幾個條件不是每次都要使用,那麼我們就可以
  2. //透過判斷是否拼接到sql中
  3.    id="queryById" resultMap="BascResultMap" parameterType="entity">
  4.     SELECT *  from entity
  5.     
  6.          test="name!=null">
  7.             name like concat('%',concat(#{name},'%'))
  8.         
  •     
  •   

choose (when, otherwise)標簽

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

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

  1.   
  2.  id="getUserList_choose" resultMap="resultMap_user" parameterType="com.yiibai.pojo.User">  
  3.     SELECT *  
  4.       FROM User u   
  5.       
  6.           
  7.              test="username !=null ">  
  8.                 u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')  
  9.             

 >  

  •              test="sex != null and sex != '' ">  
  •                 AND u.sex = #{sex, jdbcType=INTEGER}  
  •             

 >  

  •              test="birthday != null ">  
  •                 AND u.birthday = #{birthday, jdbcType=DATE}  
  •             

 >  

  •               
  •             

  

  •         

  

  •     

    

selectKey 標簽

在insert陳述句中,在Oracle經常使用序列、在MySQL中使用函式來自動生成插入表的主鍵,而且需要方法能傳回這個生成主鍵。使用myBatis的selectKey標簽可以實現這個效果。
下麵例子,使用mysql資料庫自定義函式nextval(‘student’),用來生成一個key,並把他設定到傳入的物體類中的studentId屬性上。所以在執行完此方法後,邊可以透過這個物體類獲取生成的key。

  1.   
  2.  id="createStudentAutoKey" parameterType="liming.student.manager.data.model.StudentEntity" keyProperty="studentId">  
  3.      keyProperty="studentId" resultType="String" order="BEFORE">  
  4.         select nextval('student')  
  5.     

  

  •     INSERT INTO STUDENT_TBL(STUDENT_ID,  
  •                             STUDENT_NAME,  
  •                             STUDENT_SEX,  
  •                             STUDENT_BIRTHDAY,  
  •                             STUDENT_PHOTO,  
  •                             CLASS_ID,  
  •                             PLACE_ID)  
  •     VALUES (#{studentId},  
  •             #{studentName},  
  •             #{studentSex},  
  •             #{studentBirthday},  
  •             #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  •             #{classId},  
  •             #{placeId})  

呼叫介面方法,和獲取自動生成key

  1. StudentEntity entity = new StudentEntity();  
  2. entity.setStudentName("黎明你好");  
  3. entity.setStudentSex(1);  
  4. entity.setStudentBirthday(DateUtil.parse("1985-05-28"));  
  5. entity.setClassId("20000001");  
  6. entity.setPlaceId("70000001");  
  7. this.dynamicSqlMapper.createStudentAutoKey(entity);  
  8. System.out.println("新增學生ID: " + entity.getStudentId());

if標簽

if標簽可用在許多型別的sql陳述句中,我們以查詢為例。首先看一個很普通的查詢:

  1.   
  2.  id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST   
  4. WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  

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

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

  1.   
  2.  id="getStudentList_if" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.      WHERE  
  12.      test="studentName !=null ">  
  13.         ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.     

  

  •      test="studentSex != null and studentSex != '' ">  
  •         AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  •     

  

  •      test="studentBirthday != null ">  
  •         AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  •     

  

  •      test="classId != null and classId!= '' ">  
  •         AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  •     

  

  •      test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  •         AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  •     

  

  •      test="placeId != null and placeId != '' ">  
  •         AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  •     

  

  •      test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  •         AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  •     

  

  •      test="studentId != null and studentId != '' ">  
  •         AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  •     

   

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

  1. public void select_test_2_1() {  
  2.     StudentEntity entity = new StudentEntity();  
  3.     entity.setStudentName("");  
  4.     entity.setStudentSex(1);  
  5.     entity.setStudentBirthday(DateUtil.parse("1985-05-28"));  
  6.     entity.setClassId("20000001");  
  7.     //entity.setPlaceId("70000001");  
  8.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);  
  9.     for (StudentEntity e : list) {  
  10.         System.out.println(e.toString());  
  11.     }  
  12. }

if + where 的條件判斷

當where中的條件使用的if標簽較多時,這樣的組合可能會導致錯誤。我們以在3.1中的查詢陳述句為例子,當java程式碼按如下方法呼叫時:

  1. @Test  
  2. public void select_test_2_1() {  
  3.     StudentEntity entity = new StudentEntity();  
  4.     entity.setStudentName(null);  
  5.     entity.setStudentSex(1);  
  6.     List list = this.dynamicSqlMapper.getStudentList_if(entity);  
  7.     for (StudentEntity e : list) {  
  8.         System.out.println(e.toString());  
  9.     }  
  10. }

如果上面例子,引數studentName為null,將不會進行STUDENT_NAME列的判斷,則會直接導“WHERE AND”關鍵字多餘的錯誤SQL。
這時我們可以使用where動態陳述句來解決。這個“where”標簽會知道如果它包含的標簽中有傳回值的話,它就插入一個‘where’。此外,如果標簽傳回的內容是以AND 或OR 開頭的,則它會剔除掉。
上面例子修改為:

  1.   
  2.  id="getStudentList_whereIf" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.       
  12.          test="studentName !=null ">  
  13.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.         

  

  •          test="studentSex != null and studentSex != '' ">  
  •             AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  •         

  

  •          test="studentBirthday != null ">  
  •             AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  •         

  

  •          test="classId != null and classId!= '' ">  
  •             AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  •         

  

  •          test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  •             AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  •         

  

  •          test="placeId != null and placeId != '' ">  
  •             AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  •         

  

  •          test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  •             AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  •         

  

  •          test="studentId != null and studentId != '' ">  
  •             AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  •         

  

  •     

    

if + set實現修改陳述句

當update陳述句中沒有使用if標簽時,如果有一個引數為null,都會導致錯誤。
當在update陳述句中使用if標簽時,如果前面的if沒有執行,則或導致逗號多餘錯誤。使用set標簽可以將動態的配置SET 關鍵字,和剔除追加到條件末尾的任何不相關的逗號。使用if+set標簽修改後,如果某項為null則不進行更新,而是保持資料庫原值。如下示例:

  1.   
  2.  id="updateStudent_if_set" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     UPDATE STUDENT_TBL  
  4.       
  5.          test="studentName != null and studentName != '' ">  
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},  
  7.         

  

  •          test="studentSex != null and studentSex != '' ">  
  •             STUDENT_TBL.STUDENT_SEX = #{studentSex},  
  •         

  

  •          test="studentBirthday != null ">  
  •             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
  •         

  

  •          test="studentPhoto != null ">  
  •             STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  •         

  

  •          test="classId != '' ">  
  •             STUDENT_TBL.CLASS_ID = #{classId}  
  •         

  

  •          test="placeId != '' ">  
  •             STUDENT_TBL.PLACE_ID = #{placeId}  
  •         

  

  •     

  

  •     WHERE STUDENT_TBL.STUDENT_ID = #{studentId};      

if + trim代替where/set標簽

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

trim代替where

  1.   
  2.  id="getStudentList_if_trim" resultMap="resultMap_studentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.      prefix="WHERE" prefixOverrides="AND|OR">  
  12.          test="studentName !=null ">  
  13.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.         

  

  •          test="studentSex != null and studentSex != '' ">  
  •             AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  •         

  

  •          test="studentBirthday != null ">  
  •             AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  •         

  

  •          test="classId != null and classId!= '' ">  
  •             AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  •         

  

  •          test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  •             AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  •         

  

  •          test="placeId != null and placeId != '' ">  
  •             AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  •         

  

  •          test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  •             AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  •         

  

  •          test="studentId != null and studentId != '' ">  
  •             AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  •         

  

  •     

     

trim代替set

  1.   
  2.  id="updateStudent_if_trim" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     UPDATE STUDENT_TBL  
  4.      prefix="SET" suffixOverrides=",">  
  5.          test="studentName != null and studentName != '' ">  
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},  
  7.         

  

  •          test="studentSex != null and studentSex != '' ">  
  •             STUDENT_TBL.STUDENT_SEX = #{studentSex},  
  •         

  

  •          test="studentBirthday != null ">  
  •             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
  •         

  

  •          test="studentPhoto != null ">  
  •             STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  •         

  

  •          test="classId != '' ">  
  •             STUDENT_TBL.CLASS_ID = #{classId},  
  •         

  

  •          test="placeId != '' ">  
  •             STUDENT_TBL.PLACE_ID = #{placeId}  
  •         

  

  •     

  

  •     WHERE STUDENT_TBL.STUDENT_ID = #{studentId}  

foreach

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

foreach元素是非常強大的,它允許你指定一個集合,宣告集合項和索引變數,它們可以用在元素體內。它也允許你指定開放和關閉的字串,在迭代之間放置分隔符。這個元素是很智慧的,它不會偶然地附加多餘的分隔符。

註意:你可以傳遞一個List實體或者陣列作為引數物件傳給MyBatis。當你這麼做的時候,MyBatis會自動將它包裝在一個Map中,用名稱在作為鍵。List實體將會以“list”作為鍵,而陣列實體將會以“array”作為鍵。

這個部分是對關於XML配置檔案和XML對映檔案的而討論的。下一部分將詳細討論Java API,所以你可以得到你已經建立的最有效的對映。

引數為array示例的寫法

介面的方法宣告:

  1. public List<StudentEntity> getStudentListByClassIds_foreach_array(String[] classIds);

動態SQL陳述句:

  1.   
  2.  id="getStudentListByClassIds_foreach_array" resultMap="resultMap_studentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST  
  11.       WHERE ST.CLASS_ID IN   
  12.       collection="array" item="classIds"  open="(" separator="," close=")">  
  13.         #{classIds}  
  14.      

  

測試程式碼,查詢學生中,在20000001、20000002這兩個班級的學生:

  1. @Test  
  2. public void test7_foreach() {  
  3.     String[] classIds = { "20000001", "20000002" };  
  4.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_array(classIds);  
  5.     for (StudentEntity e : list) {  
  6.         System.out.println(e.toString());  
  7.     }  
  8. }

2引數為list示例的寫法
介面的方法宣告:

  1. public List<StudentEntity> getStudentListByClassIds_foreach_list(List<String> classIdList);

動態SQL陳述句:

  1.   
  2.  id="getStudentListByClassIds_foreach_list" resultMap="resultMap_studentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST  
  11.       WHERE ST.CLASS_ID IN   
  12.       collection="list" item="classIdList"  open="(" separator="," close=")">  
  13.         #{classIdList}  
  14.      

  

測試程式碼,查詢學生中,在20000001、20000002這兩個班級的學生:

  1. @Test  
  2. public void test7_2_foreach() {  
  3.     ArrayList<String> classIdList = new ArrayList<String>();  
  4.     classIdList.add("20000001");  
  5.     classIdList.add("20000002");  
  6.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_list(classIdList);  
  7.     for (StudentEntity e : list) {  
  8.         System.out.println(e.toString());  
  9.          }

sql片段標簽:透過該標簽可定義能復用的sql陳述句片段,在執行sql陳述句標簽中直接取用即可。這樣既可以提高編碼效率,還能有效簡化程式碼,提高可讀性

需要配置的屬性:id=”” >>>表示需要改sql陳述句片段的唯一標識

取用:透過標簽取用,refid=”” 中的值指向需要取用的中的id=“”屬性

  1.   
  2.  id="orderAndItem">  
  3.     o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count  
  4.   

  

  •  
  •   id="findOrderAndItemsByOid" parameterType="java.lang.String" resultMap="BaseResultMap">  
  •     select  
  •   
  •      refid="orderAndItem" />  
  •     from ordertable o  
  •     join orderitem i on o.orderitem_id = i.orderitem_id  
  •     where o.order_id = #{orderId}  
  •   

END

    已同步到看一看
    贊(0)

    分享創造快樂