Mybatis中的批量添加和批量删除

在程序中封装了一个List集合对象,然后需要把该集合中的实体插入到数据库中,项目使用了Spring MVC +MyBatis的配置,使用MyBatis批量插入。

主要是用foreach标签,它可以在SQL语句中进行迭代一个集合。

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

item表示集合中每一个元素进行迭代时的别名,

index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,

open表示该语句以什么开始,

separator表示在每次进行迭代之间以什么符号作为分隔 符,

close表示以什么结束,

在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的。

1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

     2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

举例:

一:批量插入一个集合

方法:

public Long insertPriceHistoryList(List<TmallPriceHistory> list) ;

参数:

List<TmallPriceHistory> list;

SQL语句:

<insert id="insertPriceHistoryList" parameterType="java.util.List" >
insert into 
`tmall_price_history_copy`
(
`sid`,
`third_request_history_sid`,
`shopinProSid`,
`shopinSku`,
`tmallNum_iid`,
`shopinProDetailSid`,
`tmallSkuId`,
`tmallSkuProperties`,
`propertiesName`,
`price`,
`createTime`,
`operateTime`,
`tmallPriceTime`,
`status`,
`memo`,
`type`
) values
<foreach collection="list"  item="item"  index="index"  separator=",">
(
#{item.sid},
#{item.third_request_history_sid},
#{item.shopinProSid},
#{item.shopinSku},
#{item.tmallNum_iid},
#{item.shopinProDetailSid},
#{item.tmallSkuId},
#{item.tmallSkuProperties},
#{item.propertiesName},
#{item.price},
#{item.createTime},
#{item.operateTime},
#{item.tmallPriceTime},
#{item.status},
#{item.memo},
#{item.type}
)
</foreach>
</insert>

二:批量删除list集合

方法:

public Long deletePriceHistoryList(List<TmallPriceHistory> priceHistoryList) ;

参数:

List<TmallPriceHistory> priceHistoryList;

SQL语句:

<delete id="deletePriceHistoryList" parameterType="java.util.List">
delete
from
`tmall_price_history`
where
  `sid` 
 in
 <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item.sid}
</foreach>
</delete>


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