Mybatis--如何返回insert后的主键值

不返回自增主键的方法

<insert id="insertFollowInfo" >
		INSERT INTO follow_info(podcast_id,g_user_id,follow_time,create_time,update_time)
			VALUES(#{podcastId},#{gUserId},#{followTime},#{createTime},#{updateTime})
	</insert>

返回自增主键的方法

<!-- useGeneratedKeys 设置为true之后,mybatis会使用JDBC的getGeneratedKeys 方法取出来由数据库内部生成的主键。
获得到主键后将其赋值给keyProperty配置的id属性。当需要设置多个属性时,使用逗号隔开,这种情况下通常还需要设置
keyColumn属性,按顺序指定数据库的列,这里列的值会和keyProperty配置的属性一一对应。由于要使用数据库返回的主键值,
所以SQL上下两部分的列中去掉了id列和对应的#{id}列 -->
<insert id="insertFollowInfo" parameterType="com.shareit.*.FollowInfo" keyProperty="id" useGeneratedKeys="true" keyColumn="id">
		INSERT INTO follow_info(podcast_id,g_user_id,follow_time,create_time,update_time)
			VALUES(#{podcastId},#{gUserId},#{followTime},#{createTime},#{updateTime})
	</insert>

此时,需要从insert的对象中找到对应的id,其返回值是insert的数量,当然正常值应该是1,即插入了一行。

如果是非自增主键

此时需要通过selectKey标签的select last_insert_id()来获取

<insert id="insertFollowInfo" >
		INSERT INTO follow_info(podcast_id,g_user_id,follow_time,create_time,update_time)
			VALUES(#{podcastId},#{gUserId},#{followTime},#{createTime},#{updateTime})
<selectKey keyColumn="id" resultType="Long" keyProperty="id" order="AFTER">
   select last_insert_id()
  </selectKey>
</insert>

参考:

https://blog.csdn.net/yinlell/article/details/94733362

发布了362 篇原创文章 · 获赞 144 · 访问量 110万+

猜你喜欢

转载自blog.csdn.net/FENGQIYUNRAN/article/details/103555189
今日推荐