mybatis批量新增和批量刪除
阿新 • • 發佈:2020-11-16
<!--mybatis批量新增-->
<insert id="save" parameterType="list" keyProperty="sid" useGeneratedKeys="true"> <!--新增成功返回自增的主鍵-->
insert into
<include refid="tableName"/> <!--表名我這裡用的是sql標籤-->
(<include refid="column"/>) <!--新增的欄位sql標籤-->
values
<foreach collection="list" item="item" separator=","> <!--使用了foreach-->
(<include refid="sc"/>)
</foreach>
</insert>
<!--批量新增測試-->
//讀取配置檔案Hui.xml
InputStream config = Resources.getResourceAsStream("config/Hui.xml");
//根據配置檔案構建SqlSessionFactory
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(config);
//通過SqlSessionFactory建立SQLSession
SqlSession session = build.openSession();
List list = new LinkedList();
Map map = new HashMap();
map.put("shopName","yangRou");
map.put("shopPrice",0);
map.put("shopType","rou");
Map map1 = new HashMap();
map1.put("shopName","yangRou");
map1.put("shopPrice",10);
map1.put("shopType","rou");
list.add(map);
list.add(map1);
int insert = session.insert("com.hp.dao.ShopDao.save", list);
System.out.println(map.get("sid")); //獲取自增的主鍵
session.commit();
System.out.println(insert);
<!--mybatis批量刪除-->
<delete id="del" parameterType="list">
delete
from
<include refid="tableName"/> <!--表名我這裡用的是sql標籤-->
<where>
id in
<foreach collection="list" item="item" open="(" separator=", " close=")"> <!--使用了foreach-->
#{item}
</foreach>
</where>
</delete>
<!--批量刪除測試-->
//讀取配置檔案Hui.xml
InputStream config = Resources.getResourceAsStream("config/Hui.xml");
//根據配置檔案構建SqlSessionFactory
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(config);
//通過SqlSessionFactory建立SQLSession
SqlSession session = build.openSession();
List list = new LinkedList();
list.add(80);
list.add(81);
int delete = session.delete("com.hp.dao.ShopDao.del", list);
session.commit();
System.out.println(delete);