我是靠谱客的博主 细腻篮球,这篇文章主要介绍MyBatis 使用 foreach 批量插入教程,现在分享给大家,希望可以做个参考。

教程

单条语句插入多个值

@Mapper
public interface UserMapper {
void batchSave(List<User> userList);
}
<insert id="batchSave">
insert into user(name, password) values
<foreach collection="list" item="user" separator=",">
(#{user.name}, #{user.password})
</foreach>
</insert>
@RunWith(SpringRunner.class)
@SpringBootTest
public class SbMybatis02ApplicationTests {
@Test
public void testBatchSave(){
User user1 = new User();
user1.setName("关羽");
user1.setPassword("guanyu");
User user2 = new User();
user2.setName("张飞");
user2.setPassword("zhangfei");
List<User> userList
= new ArrayList<>();
userList.add(user1);
userList.add(user2);
userMapper.batchSave(userList);
}
}

多条语句插入多个值

@Mapper
public interface UserMapper {
void batchSave(List<User> userList);
}
<insert id="batchSave">
<foreach collection="list" item="user" separator=";">
insert into user(name, password) values
(#{user.name}, #{user.password})
</foreach>
</insert>
@RunWith(SpringRunner.class)
@SpringBootTest
public class SbMybatis02ApplicationTests {
@Test
public void testBatchSave(){
User user1 = new User();
user1.setName("关羽");
user1.setPassword("guanyu");
User user2 = new User();
user2.setName("张飞");
user2.setPassword("zhangfei");
List<User> userList
= new ArrayList<>();
userList.add(user1);
userList.add(user2);
userMapper.batchSave(userList);
}
}

Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into user(name, password) values('张飞', 'zhangfei')' at line 4 方案: jdbcUrl 添加参数 allowMultiQueries=true

jdbc:mysql://localhost:3306/db3?serverTimezone=Asia/Shanghai&allowMultiQueries=true

最后

以上就是细腻篮球最近收集整理的关于MyBatis 使用 foreach 批量插入教程的全部内容,更多相关MyBatis内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(275)

评论列表共有 0 条评论

立即
投稿
返回
顶部