insert into user(name, password) values 赞 踩 修改 Mapper 添加批量插入方法 修改映射文件 添加批量插入映射语句 测试接口 修改 Mapper 添加批量插入方法 修改映射文件 添加批量插入映射语句 修改 jdbcUrl 允许执行多条语句 测试接口 Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。
数据库------MyBatis 使用 foreach 批量插入_mybatis foreach插入
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>
jdbc:mysql://localhost:3306/db3?serverTimezone=Asia/Shanghai&allowMultiQueries=true
@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