MyBatis 標籤的使用

  • 轉載出處:https://blog.csdn.net/m0_37204491/article/details/71436872
  • 你可以傳遞一個 List 實例或者數組作爲參數對象傳給 MyBatis。當你這麼做的時候,MyBatis 會自動將它包裝在一個 Map 中,用名稱作爲鍵。List 實例將會以“list”作爲鍵,而數組實例將會以“array”作爲鍵。
  • foreach元素的屬性主要有 item,index,collection,open,separator,close。
    • item表示集合中每一個元素進行迭代時的別名,
    • index指定一個名字,用於表示在迭代過程中,每次迭代到的位置,
    • open表示該語句以什麼開始,
    • separator表示在每次進行迭代之間以什麼符號作爲分隔符,
    • close表示以什麼結束。
  • 在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,但是在不同情況下,該屬性的值是不一樣的,主要有一下3種情況:

    • 1.如果傳入的是單參數且參數類型是一個List的時候,collection屬性值爲list

    • 2.如果傳入的是單參數且參數類型是一個array數組的時候,collection的屬性值爲array

    • 3.如果傳入的參數是多個的時候,我們就需要把它們封裝成一個Map或者Object。
    • entity實體類

      public class QueryVo(){
          private User user;
          private UserCustom userCustom;
          private List<integer> ids;
      }

Mapper

 

  • <select id="find" parameterType="qo" resultMap="userResult">
        select * from `user`
        <where>
            <foreach collection="ids" open=" and id in(" close=")" 
            item="id" separator=",">
                #{id}
            </foreach>
        </where>
        limit 0,10
    </select>
  • 測試代碼

    @Test
    public void testFindByForeach(){
        UserDaoImpl dao = new UserDaoImpl();
        QueryObject queryObject = new QueryObject();
        List<String> ids = new ArrayList<>();
            ids.add("93365508879156507BA5FA7AD34ED9A10DC876DCC6BE7E08548587");
            ids.add("93365566961612F12AF562B60641B8964B99202A80720834031994");
            ids.add("9336561173424758F5F3B93D804D55AF41DE49B86EDE8D31235175");
            ids.add("2222");
            ids.add("111");
            queryObject.setIds(ids);
            List<User> userList = dao.find(queryObject);
            System.out.println(userList);
    }
  • 直接傳遞單個List
    • 傳遞List類型在編寫mapper.xml沒有區別,唯一不同的是隻有一個List參數時它的參數名爲list。
  • Mapper

    <select id="selectByList" parameterType="java.util.List" resultType="user">
    select * from user 
    <where>
    <!-- 傳遞List,List中是pojo -->
    <if test="list!=null">
        <foreach collection="list" item="item" open="and id in("separator=","close=")">
              #{item.id} 
        </foreach>
    </if>
    </where>
    </select>
  • 傳遞單個數組(數組中是pojo):

    <!-- 傳遞數組綜合查詢用戶信息 -->
    <select id="findByArray" parameterType="Object[]" resultType="user">
    select * from user 
    <where>
    <!-- 傳遞數組 -->
    <if test="array!=null">
    <foreach collection="array" index="index" item="item" open="and id in("separator=","close=")">
                #{item.id} 
    </foreach>
    </if>
    </where>
    </select>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章