在MyBatis中,获取主键的方法有两种常用的方式:
<insert id="insertUser" parameterType="User">
<selectKey keyProperty="id" order="AFTER" resultType="int">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
<insert id="insertUser" parameterType="User">
<selectKey keyProperty="id" order="AFTER" resultType="int">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
这两种方法都是在插入数据后立即执行一个SQL语句来获取主键值,然后将其设置到实体对象中的主键属性上。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: MyBatis中sqlId命名规范是什么