您的位置:首页 > 其它

MyBatis插入后返回主键

2017-12-30 21:59 162 查看

插入单条记录返回主键:

<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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis