MyBatis如何实现批量插入?
方式一、打开批量插入的 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
for (int i = 36; i <= 45; i++) {
userMapper.insertUser(new User(i, "yiidian" + i));
}
sqlSession.commit();
sqlSession.close();
方式二、拼接批量插入的 insert SQL
//Java 代码
List<User> userList = new ArrayList<>();
for (int i = 46; i <= 55; i++) {
userList.add(new User(i,"yiidian" + i));
}
userMapper.insertUserBatch(userList);
<!--Mapper xml 中配置-->
<insert id="insertUserBatch" parameterType="java.util.List">
insert into user values
<foreach collection="list" item="item" separator =",">
(#{item.id}, #{item.name})
</foreach>
</insert>