MyBatis 批量插入数据
通过 动态sql 中 foreach 来进行批量保存
<!-- 批量插入 -->
<!-- void addUser(@Param("users") List<User> users); -->
<insert id="addUser">
insert into user (username,password)
values
<foreach collection="users" item="user" separator=",">
(#{user.username},#{user.password})
</foreach>
</insert>
编写测试
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis/mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过SqlSessionFactory来openSession
SqlSession session = sqlSessionFactory.openSession(true);//打开事务自动提交
try {
UserDao mapper = session.getMapper(UserDao.class);
List<User> users = new ArrayList<>();
users.add(new User("Aiden1","123456"));
users.add(new User("Aiden2","123456"));
users.add(new User("Aiden3","123456"));
mapper.addUser(users);
}finally {
//释放资源
session.close();
}
}
运行结果
MySQL 支持 values( ), ( ), ( ) 的语法 则可以使用 foreach 遍历