Mybatis batch insert self-increasing primary key acquisition

Recently, I am doing a Demo project with SpringBoot + Mybatis + MySQL. There is a Mapper interface that inserts student data in batches.

SpringBoot version is 1.5.6, Mybatis version is 3.4.5, MySQL version is 5.7.20

The primary key of the Student table is Id, Auto Increment, and the batch insert code is written according to the MyBatis official website guide.

The code of StudentMapper is as follows

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

The code of StudentMapper.xml is as follows

 <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>

The data was inserted successfully, but when getting the list of returned Ids, an exception was thrown

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

According to the error message, it seems that Mybatis cannot recognize List with Primitive Type, but Mybatis has supported batch insertion since version 3.3.1, but now it just cannot recognize the return type.

In fact, since keyProperty="id" is set, the self-incrementing Id value has been assigned to the id property of the inserted Student object, we only need to get it from each Student object in the inserted students list, so I will insertStudents method change to

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

Although this avoids the throwing of exceptions, it is not very convenient to obtain the generated id from the Students list in the upper layer of Mapper. I hope the subsequent versions of Mybatis can solve this problem.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325906906&siteId=291194637