10 種超讚的 MyBatis 寫法!

大家好,我是不才陳某~

MyBatis 雖說給我們的開發帶來了很多的便捷,但有些地方寫起來依舊比較的麻煩,比如配置 XML 的時候,但是一個好的寫法,不僅能爲我們節省不少時間、還能能降低出錯的概率,下面就給大家分享一些優質的寫法:

1、用來循環容器的標籤 forEach

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

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

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

注意 你可以將一個 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 值

//mapper中我們要爲這個方法傳遞的是一個容器,將容器中的元素一個一個的
//拼接到xml的方法中就要使用這個forEach這個標籤了
public List<Entity> queryById(List<String> userids);
    //對應的xml中如下
    <select id="queryById" resultMap="BaseReslutMap" >
        select * FROM entity
        where id in 
        <foreach collection="userids" item="userid" index="index" open="(" separator="," close=")">
            #{userid}
        </foreach>
    </select>

2、concat 模糊查詢

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

3、choose (when, otherwise) 標籤

choose 標籤是按順序判斷其內部 when 標籤中的 test 條件出否成立,如果有一個成立,則 choose 結束。當 choose 中所有 when 的條件都不滿則時,則執行 otherwise 中的 sql。類似於 Java 的 switch 語句,choose 爲 switch,when 爲 case,otherwise 則爲 default。關注:碼猿技術專欄,回覆關鍵詞:1111 獲取阿里內部 Java 性能調優手冊!

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

<!--  choose(判斷參數) - 按順序將實體類 User 第一個不爲空的屬性作爲:where條件 -->  
<select id="getUserList_choose" resultMap="resultMap_user" parameterType="com.yiibai.pojo.User">  
    SELECT *  
      FROM User u   
    <where>  
        <choose>  
            <when test="username !=null ">  
                u.username LIKE CONCAT(CONCAT('%'#{username, jdbcType=VARCHAR}),'%')  
            </when >  
            <when test="sex != null and sex != '' ">  
                AND u.sex = #{sex, jdbcType=INTEGER}  
            </when >  
            <when test="birthday != null ">  
                AND u.birthday = #{birthday, jdbcType=DATE}  
            </when >  
            <otherwise>  
            </otherwise>  
        </choose>  
    </where>    
</select>

4、selectKey 標籤

在 insert 語句中,在 Oracle 經常使用序列、在 MySQL 中使用函數來自動生成插入表的主鍵,而且需要方法能返回這個生成主鍵。使用 myBatis 的 selectKey 標籤可以實現這個效果。

下面例子,使用 mysql 數據庫自定義函數 nextval('student'),用來生成一個 key,並把他設置到傳入的實體類中的 studentId 屬性上。所以在執行完此方法後,邊可以通過這個實體類獲取生成的 key。

<!-- 插入學生 自動主鍵-->  
<insert id="createStudentAutoKey" parameterType="liming.student.manager.data.model.StudentEntity" keyProperty="studentId">  
    <selectKey keyProperty="studentId" resultType="String" order="BEFORE">  
        select nextval('student')  
    </selectKey>  
    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})  
</insert>

調用接口方法,和獲取自動生成 key

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

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

6、if + where 的條件判斷

當 where 中的條件使用的 if 標籤較多時,這樣的組合可能會導致錯誤。我們以在 3.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>

7、if + set 實現修改語句

當 update 語句中沒有使用 if 標籤時,如果有一個參數爲 null,都會導致錯誤。

當在 update 語句中使用 if 標籤時,如果前面的 if 沒有執行,則或導致逗號多餘錯誤。使用 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>

8、if + trim 代替 where/set 標籤

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

trim 代替 where

<!-- 5.1if/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>

9、foreach

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

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

注意:你可以傳遞一個 List 實例或者數組作爲參數對象傳給 MyBatis。當你這麼做的時候,MyBatis 會自動將它包裝在一個 Map 中,用名稱在作爲鍵。List 實例將會以 “list” 作爲鍵,而數組實例將會以 “array” 作爲鍵。

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

參數爲 array 示例的寫法

接口的方法聲明:

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

動態 SQL 語句:

<!-- 7.1 foreach(循環array參數) - 作爲where中in的條件 -->  
<select id="getStudentListByClassIds_foreach_array" 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  
      WHERE ST.CLASS_ID IN   
     <foreach collection="array" item="classIds"  open="(" separator="," close=")">  
        #{classIds}  
     </foreach>  
</select>

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

@Test  
public void test7_foreach() {  
    String[] classIds = { "20000001""20000002" };  
    List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_array(classIds);  
    for (StudentEntity e : list) {  
        System.out.println(e.toString());  
    }  
}

參數爲 list 示例的寫法

接口的方法聲明:

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

動態 SQL 語句:

<!-- 7.2 foreach(循環List<String>參數) - 作爲where中in的條件 -->  
<select id="getStudentListByClassIds_foreach_list" 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  
      WHERE ST.CLASS_ID IN   
     <foreach collection="list" item="classIdList"  open="(" separator="," close=")">  
        #{classIdList}  
     </foreach>  
</select>

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

@Test  
public void test7_2_foreach() {  
    ArrayList<String> classIdList = new ArrayList<String>();  
    classIdList.add("20000001");  
    classIdList.add("20000002");  
    List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_list(classIdList);  
    for (StudentEntity e : list) {  
        System.out.println(e.toString());  
    }  
}

sql 片段標籤<sql>:通過該標籤可定義能複用的 sql 語句片段,在執行 sql 語句標籤中直接引用即可。這樣既可以提高編碼效率,還能有效簡化代碼,提高可讀性

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

引用:通過<include refid="" />標籤引用,refid="" 中的值指向需要引用的<sql>中的 id=“” 屬性

<!--定義sql片段-->  
<sql id="orderAndItem">  
o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count  
</sql>  

<select id="findOrderAndItemsByOid" parameterType="java.lang.String" resultMap="BaseResultMap">  
    select  
    <!--引用sql片段-->  
    <include refid="orderAndItem" />  
    from ordertable o  
    join orderitem i on o.orderitem_id = i.orderitem_id  
    where o.order_id = #{orderId}  
</select>
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/TvL-XGvL6vbghSbsQCYcAw