MyBatis批量插入返回主键

  网上有很多人说MyBatis不支持批量插入并且返回主键,其实这种说法有一定的误解,如果你想让MyBatis直接返回一个包含主键的list,即mapper接口中批量插入方法的返回值为List<Integer>,这样的确是不行的

  例如:录入学生成绩

  数据库:mysql

//错误的写法
public List<Integer> batchInsert(List<Student> students);

  这种想法是错误的,为了把这个错误解释得明白一点,我们还是先看看单条插入的时候是如何返回主键的吧,下面是MyBatis官方文档

  也就是说只要在insert标签里加入useGeneratedKeys="true"和keyProperty="id"即可,mapper接口这样写

public int insert(Student student);

  xml

<insert id="insert" useGeneratedKeys="true" keyProperty="id">
    insert into student (name, score) values (#{name}, #{score})
</insert>

  运行之后会发现,返回值始终是1,也就是返回值是受影响的行数。返回的主键实际上被映射到了参数student的id属性中,只需student.getId()即可得到

Student student = new Student("小明", 77);
int line = mapper.insert(student);
System.out.println("受影响的行数:" + line);
System.out.println("返回的主键:" + student.getId());

  运行结果:

  接下来说批量插入,其实一样的原理,下面是官方文档,使用foreach批量插入,返回主键的方法还是那样

  mapper接口

public int batchInsert(List<Student> students);

  xml

<insert id="batchInsert" useGeneratedKeys="true" keyProperty="id">
    insert into student (name, score) values
    <foreach collection="list" item="item" index="index" separator=",">
        (#{item.name}, #{item.score})
    </foreach>
</insert>

  测试插入

复制代码
List<Student> students = new ArrayList<Student>();
Student tom = new Student("Tom", 88);
Student jerry = new Student("Jerry", 99);
students.add(tom);
students.add(jerry);
int line = mapper.batchInsert(students);
System.out.println("受影响的行数:" + line);
for (Student student : students) {
    System.out.println("返回的主键:" + student.getId());
}
复制代码

  运行结果

  综上,MyBatis是可以批量插入并返回主键的,不过返回的主键不是在mapper接口的返回值里面(有点绕,其实很简单),而是映射到了参数的id属性里面。因此keyProperty的值必须和参数的主键属性保持一致。

 内容转自 https://www.cnblogs.com/zephyrus/archive/2017/08/21/7403127.html

原文地址:https://www.cnblogs.com/ylsx/p/14261492.html