MyBatis 使用 foreach 批量插入


MyBatis 使用 foreach 批量插入

參考博文

老司機學習MyBatis之動態SQL使用foreach在MySQL中批量插入

使用MyBatis一次性插入多條數據時候可以使用 <foreach> 標簽。

yml文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db3?serverTimezone=Asia/Shanghai&allowMultiQueries=true
    username: root
    password: root

mybatis:
  type-aliases-package: com.mozq.boot.sbmybatis02.domain
  mapper-locations: classpath:mapper/*Mapper.xml

第1種方式 單條語句插入多個值

可以使用 useGeneratedKeys 返回每個插入記錄的主鍵。

修改 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);
    }
}

第2種方式 多條語句插入多個值

如果插入的同時獲取主鍵,則只有第1條記錄可以獲取到,其他記錄獲取不到生成的主鍵。

修改 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);
    }
}

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM