1.第一种方式:
<insert id="insertStudents" useGeneratedKeys="true" keyProperty="studId"
parameterType="java.util.ArrayList">
INSERT INTO
STUDENTS(STUD_ID, NAME, EMAIL, DOB, PHONE)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.studId},#{item.name},#{item.email},#{item.dob}, #{item.phone})
</foreach>
</insert>
Mapper.xml中keyProperty和parameterType属性之间的关系
useGeneratedKeys="true" keyProperty="studId" parameterType="Student"
上述xml配置,含义为,属性studId是参数类型Student对象的主键属性。毫无疑问,Student对象中有studId属性。
useGeneratedKeys="true" keyProperty="studId" parameterType="java.util.ArrayList"
含义为:ArrayList集合中的元素的studId属性。所以,keyProperty和parameterType之间的关系,有时是直接关系,有时是间接关系。明白这个道理之后,我们就可以开始进一步阅读源码了。
SimpleExecutor和ReuseExecutor可以正确返回foreach批量插入后的id列表
配置Executor
<setting name="defaultExecutorType" value="SIMPLE" />
2.第二种方式:使用注解
public interface UserMapper
{
@Insert("insert into tbl_user (name, age) values (#{name}, #{age})")
@Options(useGeneratedKeys=true, keyProperty="userId", keyColumn="id")
void insertUser(User user);
}