最近在用SpringBoot + Mybatis + MySQL做一个Demo项目,有一个Mapper接口是批量插入学生数据。
SpringBoot版本是1.5.6,Mybatis版本是3.4.5,MySQL版本是5.7.20
Student表的主键是Id,Auto Increment,批量插入的代码是根据MyBatis官网指南写的。
StudentMapper的代码如下
@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.list
根据错误信息,貌似是Mybatis无法识别带Primitive Type的List,但是Mybatis从3.3.1版本开始已经支持批量插入,现在只是不能识别返回类型。
事实上,由于设置了keyProperty="id",自增长的Id值已经赋给插入Student对象的id属性了,我们只需要从插入的students列表中每个Student对象即可获取,因此我将insertStudents方法改为
@Mapper
public interface StudentMapper {
.....................
void insertStudents(List<Student> students);
}
虽然这样避免了异常的抛出,但是需要在Mapper的上一层中从Students列表中获取生成id,总归不是很方便,希望Mybatis的后续版本能够解决这个问题。