mybatis 批量插入自增加主键的获取

最近在用SpringBoot + Mybatis + MySQL作一个Demo项目,有一个Mapper接口是批量插入学生数据。java

SpringBoot版本是1.5.6,Mybatis版本是3.4.5,MySQL版本是5.7.20app

Student表的主键是Id,Auto Increment,批量插入的代码是根据MyBatis官网指南写的。code

StudentMapper的代码以下xml

@Mapper
public interface StudentMapper {
    .....................
    List<Integer> insertStudents(List<Student> students);
}

StudentMapper.xml的代码以下对象

<insert id="insertStudents" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id" >
    insert into employee(
                          NAME,
                          SEX,                          
                          BIRTH_DATE)
                          values
        <foreach item="item" collection="list" separator="," index="index">
            (
              #{item.name},
              #{item.sex},
              #{item.birthDate}
            )
        </foreach>
    </insert>

数据插入成功,可是在获取返回Id列表时,抛出了异常接口

xxxxxxxxx has an unsupported return type interface java.util.listrem

根据错误信息,貌似是Mybatis没法识别带Primitive Type的List,可是Mybatis从3.3.1版本开始已经支持批量插入,如今只是不能识别返回类型。it

事实上,因为设置了keyProperty="id",自增加的Id值已经赋给插入Student对象的id属性了,咱们只须要从插入的students列表中每一个Student对象便可获取,所以我将insertStudents方法改成io

@Mapper
public interface StudentMapper {
    .....................
    void insertStudents(List<Student> students);
}

虽然这样避免了异常的抛出,可是须要在Mapper的上一层中从Students列表中获取生成id,总归不是很方便,但愿Mybatis的后续版本可以解决这个问题。class

相关文章
相关标签/搜索