MyBatis實(shí)現(xiàn)批量插入操作可以通過使用foreach
標(biāo)簽來實(shí)現(xiàn)。下面是一個(gè)示例:
<insert id="batchInsert" parameterType="java.util.List">
insert into user (name, age) values
<foreach collection="list" item="item" separator=",">
(#{item.name}, #{item.age})
</foreach>
</insert>
List<User> userList = new ArrayList<>();
userList.add(new User("Alice", 20));
userList.add(new User("Bob", 25));
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.batchInsert(userList);
sqlSession.commit();
} finally {
sqlSession.close();
}
通過以上步驟,就可以實(shí)現(xiàn)使用MyBatis進(jìn)行批量插入操作。在實(shí)際應(yīng)用中,可以根據(jù)需要調(diào)整SQL語句和Java代碼,以滿足具體的業(yè)務(wù)需求。