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

相關文章
相關標籤/搜索