當前位置: 妍妍網 > 碼農

10 種超贊的 MyBatis 寫法,同事都說好用!

2024-05-06碼農

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

1 用來迴圈容器的標簽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值

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

    2 concat模糊查詢

    //比如說我們想要進行條件查詢,但是幾個條件不是每次都要使用,那麽我們就可以
    //透過判斷是否拼接到sql中
    <selectid="queryById"resultMap="BascResultMap"parameterType="entity">
    SELECT * from entity
    <where>
    <iftest="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。

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

    <!-- choose(判斷參數) - 按順序將實體類 User 第一個不為空的內容作為:where條件 -->
    <selectid="getUserList_choose"resultMap="resultMap_user"parameterType="com.yiibai.pojo.User">
    SELECT *
    FROM User u
    <where>
    <choose>
    <whentest="username !=null ">
    u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')
    </when >
    <whentest="sex != null and sex != '' ">
    AND u.sex = #{sex, jdbcType=INTEGER}
    </when >
    <whentest="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。

    <!-- 插入學生 自動主鍵-->
    <insertid="createStudentAutoKey"parameterType="liming.student.manager.data.model.StudentEntity"keyProperty="studentId">
    <selectKeykeyProperty="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.set classId("20000001");
    entity.setPlaceId("70000001");
    this.dynamicSqlMapper.createStudentAutoKey(entity);
    System.out.println("新增學生ID: " + entity.getStudentId());

    5 if標簽

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

    <!-- 查詢學生list,like姓名 -->
    <selectid="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條件 -->
    <selectid="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
    <iftest="studentName !=null ">
    ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
    </if>
    <iftest="studentSex != null and studentSex != '' ">
    AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
    </if>
    <iftest="studentBirthday != null ">
    AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}
    </if>
    <iftest=" classId != null and classId!= '' ">
    AND ST. class_ID = #{ classId, jdbcType=VARCHAR}
    </if>
    <iftest=" classEntity != null and classEntity. classId !=null and classEntity. classId !=' ' ">
    AND ST. class_ID = #{ classEntity. classId, jdbcType=VARCHAR}
    </if>
    <iftest="placeId != null and placeId != '' ">
    AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}
    </if>
    <iftest="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">
    AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}
    </if>
    <iftest="studentId != null and studentId != '' ">
    AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}
    </if>
    </select>

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

    publicvoidselect_test_2_1(){
    StudentEntity entity = new StudentEntity();
    entity.setStudentName("");
    entity.setStudentSex(1);
    entity.setStudentBirthday(DateUtil.parse("1985-05-28"));
    entity.set classId("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
    publicvoidselect_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條件 -->
    <selectid="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>
    <iftest="studentName !=null ">
    ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
    </if>
    <iftest="studentSex != null and studentSex != '' ">
    AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
    </if>
    <iftest="studentBirthday != null ">
    AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}
    </if>
    <iftest=" classId != null and classId!= '' ">
    AND ST. class_ID = #{ classId, jdbcType=VARCHAR}
    </if>
    <iftest=" classEntity != null and classEntity. classId !=null and classEntity. classId !=' ' ">
    AND ST. class_ID = #{ classEntity. classId, jdbcType=VARCHAR}
    </if>
    <iftest="placeId != null and placeId != '' ">
    AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}
    </if>
    <iftest="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">
    AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}
    </if>
    <iftest="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(判斷參數) - 將實體類不為空的內容更新 -->
    <updateid="updateStudent_if_set"parameterType="liming.student.manager.data.model.StudentEntity">
    UPDATE STUDENT_TBL
    <set>
    <iftest="studentName != null and studentName != '' ">
    STUDENT_TBL.STUDENT_NAME = #{studentName},
    </if>
    <iftest="studentSex != null and studentSex != '' ">
    STUDENT_TBL.STUDENT_SEX = #{studentSex},
    </if>
    <iftest="studentBirthday != null ">
    STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
    </if>
    <iftest="studentPhoto != null ">
    STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},
    </if>
    <iftest=" classId != '' ">
    STUDENT_TBL. class_ID = #{ classId}
    </if>
    <iftest="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條件-->
    <selectid="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
    <trimprefix="WHERE"prefixOverrides="AND|OR">
    <iftest="studentName !=null ">
    ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
    </if>
    <iftest="studentSex != null and studentSex != '' ">
    AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
    </if>
    <iftest="studentBirthday != null ">
    AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}
    </if>
    <iftest=" classId != null and classId!= '' ">
    AND ST. class_ID = #{ classId, jdbcType=VARCHAR}
    </if>
    <iftest=" classEntity != null and classEntity. classId !=null and classEntity. classId !=' ' ">
    AND ST. class_ID = #{ classEntity. classId, jdbcType=VARCHAR}
    </if>
    <iftest="placeId != null and placeId != '' ">
    AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}
    </if>
    <iftest="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">
    AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}
    </if>
    <iftest="studentId != null and studentId != '' ">
    AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}
    </if>
    </trim>
    </select>

    trim代替set

    <!-- 5.2 if/trim代替set(判斷參數) - 將實體類不為空的內容更新 -->
    <updateid="updateStudent_if_trim"parameterType="liming.student.manager.data.model.StudentEntity">
    UPDATE STUDENT_TBL
    <trimprefix="SET"suffixOverrides=",">
    <iftest="studentName != null and studentName != '' ">
    STUDENT_TBL.STUDENT_NAME = #{studentName},
    </if>
    <iftest="studentSex != null and studentSex != '' ">
    STUDENT_TBL.STUDENT_SEX = #{studentSex},
    </if>
    <iftest="studentBirthday != null ">
    STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},
    </if>
    <iftest="studentPhoto != null ">
    STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},
    </if>
    <iftest=" classId != '' ">
    STUDENT_TBL. class_ID = #{ classId},
    </if>
    <iftest="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> getStudentListBy classIds_foreach_array(String[] classIds);

    動態SQL語句:

    <!-- 7.1 foreach(迴圈array參數) - 作為where中in的條件 -->
    <selectid="getStudentListBy classIds_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
    <foreachcollection="array"item=" classIds"open="("separator=","close=")">
    #{ classIds}
    </foreach>
    </select>

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

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

  • 參數為list範例的寫法

    介面的方法聲明:

    public List<StudentEntity> getStudentListBy classIds_foreach_list(List<String> classIdList); 

    動態SQL語句:

    <!-- 7.2 foreach(迴圈List<String>參數) - 作為where中in的條件 -->
    <select id="getStudentListBy classIds_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
    publicvoidtest7_2_foreach(){
    ArrayList<String> classIdList = new ArrayList<String>();
    classIdList.add("20000001");
    classIdList.add("20000002");
    List<StudentEntity> list = this.dynamicSqlMapper.getStudentListBy classIds_foreach_list( classIdList);
    for (StudentEntity e : list) {
    System.out.println(e.toString());
    }

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

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

    參照:透過 <include refid="" /> 標簽參照,refid="" 中的值指向需要參照的 <sql> 中的id=「」內容

    <!--定義sql片段-->
    <sqlid="orderAndItem">
    o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count
    </sql>
    <selectid="findOrderAndItemsByOid"parameterType="java.lang.String"resultMap="BaseResultMap">
    select
    <!--參照sql片段-->
    <includerefid="orderAndItem" />
    from ordertable o
    join orderitem i on o.orderitem_id = i.orderitem_id
    where o.order_id = #{orderId}
    </select>

    blog.csdn.net/smile_lg/article/details/71215619

  • >>

    END

    精品資料,超贊福利,免費領

    微信掃碼/長按辨識 添加【技術交流群

    群內每天分享精品學習資料

    最近開發整理了一個用於速刷面試題的小程式;其中收錄了上千道常見面試題及答案(包含基礎並行JVMMySQLRedisSpringSpringMVCSpringBootSpringCloud訊息佇列等多個型別),歡迎您的使用。

    👇👇

    👇點選"閱讀原文",獲取更多資料(持續更新中