插入单条记录返回主键:
<insert id="insertOne" parameterType="User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user
(id,name,age,sex,job,birthday,authority_id)
VALUES
(#{id},#{name},#{age},#{sex},#{job},#{birthday},
#{authorityId})
</insert>
批量插入返回主键:
<insert id="insertBatch" parameterType="List" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(
id,name,age,sex,job,birthday,authority_id) VALUES
<foreach collection="list" item="item" index="index"
separator=",">
(#{item.id},#{item.name},#{item.age},#{item.sex},
#{item.job},#{item.birthday},#{item.authorityId})
</foreach>
</insert>
返回主键主要是useGeneratedKeys=”true”和keyProperty=”id”在起作用。
useGeneratedKeys=”true”表示开启JDBC的getGenereatedKeys方法获取主键,keyProperty=”id”表示将主键赋值到对象的id属性中。
注意:批量插入返回主键需要将MyBatis的版本升级到3.3.1以上。并且在数据库的url后要加上开启批量操作的指令:
&allowMultiQueries=true