mybatis 操作(批量插入,批量修改,批量刪除, 分頁查詢)

mybatis 操作(批量插入,批量修改,批量刪除,分頁查詢)

環境描述
- mybatis 3.2 ;
- mysql數據庫
- java開發語言

1.批量插入

mapper 類方法

int insertBatch(List<ShoppingCartBean> goodsList);

XML 配置


<insert id="insertBatch" parameterType="java.util.List">

   insert into th_shopping_Cart 

    (itemCode, userId, number)

   values

   <foreach collection="list" item="item" index="index" separator=",">

    (#{item.itemCode},#{item.userId},#{item.number})

   </foreach>

</insert>

2. 分頁查詢

頁面請求參數
- 頁面顯示條數 size
- 第page頁面

返回結果
- 所有記錄條目總數:totalNum
- 當前page頁
- 每頁記錄數pageSize
- 記錄列表list

mapper類方法

// 查詢第page頁的所有記錄
List<ShoppingCartBean> selectByUserId(String userId, Integer start, Integer size);
// 查詢所有記錄數量
int selectCount(String userId);

* xml配置 *


  <select id="selectByUserId" resultMap="BaseResultMap">

    select 

    <include refid="Base_Column_List" />

    from th_shopping_Cart

    where userId =#{0}
    // start = (page - 1)* size 
    order by createTime DESC limit #{1},#{2}
  </select>

  <select id="selectCount" resultType="java.lang.Integer">

     SELECT COUNT(userId) AS _count 

     FROM `th_shopping_Cart`

     WHERE userId=#{0} 

  </select>

3.mybatis 批量修改

url配置
在mysql數據庫連接上增加 &allowMultiQueries=true

例如:

jdbc:mysql://*******:3306/tohome?autoReconnect=true&autoReconnectForPools=true&interactiveClient=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true

mapper類方法

    //參數爲List<T>
int updateBatch(List<ShoppingCartBean> list);

XML配置邏輯

<update id="updateBatch" parameterType="java.util.List">
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update th_shopping_Cart 
        <set>
            number=${item.number}
        </set>
        where userId='${item.userId}' and itemCode='${item.itemCode}'
    </foreach>
  </update>

4.批量刪除

XML配置

<delete id="deleteBatch" parameterType="com.morning.star.tohome.store.entity.ShoppingItems">
    delete from th_shopping_Cart
    where userId =#{userId}

    <if test="null!=list and list.size > 0">
        and itemCode in

         <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
            #{item.itemCode}
    </foreach>
    </if>
  </delete>
  • 其中我將userId字段和List封裝到一個實體對象中了。
  • 在If 中判斷是否不爲空

————————————結束———————————-

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章