<sql id="tableName">
shop
</sql>
<sql id="column">
shopName,
shopPrice,
shopType
</sql>
<sql id="sc">
#{item.shopName},
#{item.shopPrice},
#{item.shopType}
</sql>
<!--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);