在MyBatis中,经常会使用到自增主键,但是在一个方法体内插入后如何获取自增后的主键呢?
我们知道insert和insertSelective两个方法都会有一个Integer类型返回值,它是不是我们要的自增主键呢?答案是:当然不是!
MyBatis当然知道我们的这个需求,也提供了对应的解决方案,而且是两种。接下来我们一起看看吧
在插入元素后我们查询一下最后一条数据的id,不就可以拿到这个对象的id了吗
<insert id="insertSelective" parameterType="cn.rayfoo.dao.User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
name,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
</trim>
</insert>
设置useGeneratedKeys为true
指定keyProperty为主键的字段名称
<insert id="insertSelective" parameterType="cn.rayfoo.dao.User" useGeneratedKeys="true" keyProperty="id">
</insert>
原文:https://www.cnblogs.com/zhangruifeng/p/12715194.html