数据库------MyBatis 使用 foreach 批量插入

MyBatis 使用 foreach 批量插入

  1. 第1种方式 单条语句插入多个值

修改 Mapper 添加批量插入方法

@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);
    }
}
  1. 第2种方式 多条语句插入多个值

修改 Mapper 添加批量插入方法

@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>

修改 jdbcUrl 允许执行多条语句

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);
    }
}
  1. bugs
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值