MyBatis批量插入返回自增ID列表

最近使用 Mybatis 写了很多批量插入的代码,其中也有时候需要返回自增ID列表,本文稍微介绍一下需要注意的地方。

这里为了提供一个简单的示例,以批量插入用户为例

代码地址:https://github.com/saysky/sensboot

 

先说下原理

批量插入返回自增ID列表和普通插入返回自增ID是一样的,通常只需要在 mapper.xml 的 <insert> 上添加属性 useGeneratedKeys="true" keyProperty="id" 就能实现插入成功后,mybatis 会把获得的自增ID set 到对象里,如自动 set 到 user 对象的 id 属性里,而非通过返回值获得ID或ID列表。

 

一、代码如下

1.实体类 User.java

  1. package com.liuyanzhao.sens.entity;
  2.  
  3. import lombok.Data;
  4.  
  5. import java.io.Serializable;
  6. import java.util.Date;
  7.  
  8. /**
  9.  * <pre>
  10.  *     用户信息
  11.  * </pre>
  12.  *
  13.  * @author : saysky
  14.  * @date : 2017/11/14
  15.  */
  16. @Data
  17. public class User implements Serializable {
  18.  
  19.     private static final long serialVersionUID = -5144055068797033748L;
  20.  
  21.     /**
  22.      * 编号,自增
  23.      */
  24.     private Long id;
  25.  
  26.     /**
  27.      * 用户名
  28.      */
  29.     private String username;
  30.  
  31.     /**
  32.      * 显示名称
  33.      */
  34.     private String nickname;
  35.  
  36.     /**
  37.      * 密码
  38.      */
  39.     private String password;
  40.  
  41.     /**
  42.      * 邮箱
  43.      */
  44.     private String email;
  45.  
  46.     /**
  47.      * 头像
  48.      */
  49.     private String avatar;
  50.  
  51.     /**
  52.      * 0 正常
  53.      * 1 禁用
  54.      * 2 已删除
  55.      */
  56.     private Integer status = 0;
  57.  
  58.     /**
  59.      * 创建时间
  60.      */
  61.     private Date createdTime;
  62.  
  63.     /**
  64.      * 创建人用户名
  65.      */
  66.     private String createdBy;
  67.  
  68.     /**
  69.      * 更新时间
  70.      */
  71.     private Date updatedTime;
  72.  
  73.     /**
  74.      * 更新人用户名
  75.      */
  76.     private String updatedBy;
  77.  
  78.  
  79.     public User() {
  80.     }
  81.  
  82.     public User(String username, String nickname, String password, String email, String avatar, Integer status, Date createdTime, String createdBy, Date updatedTime, String updatedBy) {
  83.         this.username = username;
  84.         this.nickname = nickname;
  85.         this.password = password;
  86.         this.email = email;
  87.         this.avatar = avatar;
  88.         this.status = status;
  89.         this.createdTime = createdTime;
  90.         this.createdBy = createdBy;
  91.         this.updatedTime = updatedTime;
  92.         this.updatedBy = updatedBy;
  93.     }
  94. }

 

2. UserMapper.java

  1. package com.liuyanzhao.sens.mapper;
  2.  
  3. import com.liuyanzhao.sens.entity.User;
  4. import org.apache.ibatis.annotations.Mapper;
  5.  
  6. import java.util.List;
  7.  
  8. /**
  9.  * @author liuyanzhao
  10.  */
  11. @Mapper
  12. public interface UserMapper  {
  13.  
  14.     /**
  15.      * 批量插入
  16.      * @param users
  17.      */
  18.     void batchInsert(List<User> users);
  19. }

 

3.UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.liuyanzhao.sens.mapper.UserMapper">
  4.  
  5.  
  6.     <insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
  7.         INSERT INTO `user`
  8.         (
  9.             username, nickname, password, email,
  10.             avatar, status, created_time, created_by,
  11.             updated_time, updated_by
  12.         )
  13.         VALUES
  14.         <foreach collection="list" item="item" separator=",">
  15.         (
  16.             #{item.username}, #{item.nickname}, #{item.password}, #{item.email},
  17.             #{item.avatar},  #{item.status},  #{item.createdTime},  #{item.createdBy},
  18.             #{item.updatedTime},  #{item.updatedBy}
  19.         )
  20.         </foreach>
  21.     </insert>
  22.  
  23. </mapper>

主要关注  useGeneratedKeys="true" keyColumn="id" keyProperty="id"

 

二、测试类

  1. package com.liuyanzhao.sens.mapper;
  2.  
  3. import com.liuyanzhao.sens.entity.User;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9.  
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.List;
  13. import java.util.stream.Collectors;
  14.  
  15.  
  16. /**
  17.  * @author 言曌
  18.  * @date 2020-01-01 16:10
  19.  */
  20.  
  21. @SpringBootTest
  22. @RunWith(SpringRunner.class)
  23. public class UserMapperTest {
  24.  
  25.     @Autowired
  26.     private UserMapper userMapper;
  27.  
  28.     /**
  29.      * 测试批量插入返回自动ID列表
  30.      */
  31.     @Test
  32.     public void batchInsert() {
  33.         Date now = new Date();
  34.         List<User> userList = new ArrayList<>();
  35.         User user = new User("zhangsan", "张三", "111111", "zhangsan@123.com", "", 1, now, "system", now, "system");
  36.         User user2 = new User("lisi", "李四", "111111", "lisi@123.com", "", 1, now, "system", now, "system");
  37.         User user3 = new User("wangwu", "王五", "111111", "wangwu@123.com", "", 1, now, "system", now, "system");
  38.         User user4 = new User("liliu", "李六", "111111", "liliu@123.com", "", 1, now, "system", now, "system");
  39.         User user5 = new User("chenqi", "陈七", "111111", "chenqi@123.com", "", 1, now, "system", now, "system");
  40.         userList.add(user);
  41.         userList.add(user2);
  42.         userList.add(user3);
  43.         userList.add(user4);
  44.         userList.add(user5);
  45.         userMapper.batchInsert(userList);
  46.  
  47.         // 获得ID列表
  48.         List<Long> userIdList = userList.stream().map(p -> p.getId()).collect(Collectors.toList());
  49.         System.out.println(userIdList);
  50.     }
  51. }

batchInsert 方法执行完毕后, userList 中每个 user 对象的id都被赋值了,且其值和数据库的id一致。

 

三、需要注意

关于这个批量导入返回id列表需要注意以下几点

  1. 确保 mybatis 版本在 3.3.1 以上
  2. batchInsert 方法上不能加 @param()
  3. batchInsert 方法只能一个参数
  4. batchInsert 返回值为 Integer 或 void,不能写 List
  5. 如果你的自增id数据库字段和实体类属性不一致,如 user_id 和 userId, 需要写成useGeneratedKeys="true" keyColumn="user_id" keyProperty="userId"

 

https://liuyanzhao.com/10056.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值