首先int i = userMapper.insertSelective(user),这里返回的并不是主键自增id,而是成功插入的条数。insert完成之后再去查询得到id,这样显然不行,很可能获取到的id不是自己想要的那条数据的id,只有在insert的过程中获取到id,再将其包装在结果集中一起返回,这样才能保证返回id的准确性。
如果想获取主键自增id,可以使用mybatis提供的两种方式:
方式一:mybatis的selectKey标签配合sql语句就可以实现这一需求
详解
keyProperty属性表示要查询的主键的名字,就是主键字段对应实体类的属性。
order属性有两个值,即after,before;after表示在insert之后执行SELECT LAST_INSERT_ID(),一般用于主键自增时,得到的就是自增长生成的id,而before表示在insert之前执行SELECT LAST_INSERT_ID(),一般用于非自增主键,得到的是传入的对象中主键的值,一般是用户生成的uuid。
resultType属性表示主键的类型,一般要么是Integer,要么是String
将selectKey标签的内容放入insert语句中就好了
代码示例:
<insert id="insert">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO activity_template_log(
activity_template_no,
start_time,
end_time,
status,
create_time
) VALUES (
#{activityTemplateNo},
#{startTime},
#{endTime},
#{status},
#{createTime}
)
</insert>
这里数据库的表结构主键都是自增长,所以selectKey标签中order属性必须是大写AFTER。
如果将order属性改成BEFORE,查询的主键id是对象的id的值,而不是自增长生成的id的值,对象的属性未赋值,自动初始化的值是0,所以此处主键的值为0,改成BEFORE取的就是对象主键的值。
方式二:在insert标签中加入useGeneratedKeys和keyProperty属性也可以(useGeneratedKeys是使用生成的主键的意思)
详解:
是否使用 useGeneratedKeys 开关为true
keyProperty对应的就是要返回的字段名称
在insert标签中加入useGeneratedKeys和keyProperty属性即可,即:useGeneratedKeys=“true” keyProperty=“id”
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT INTO activity_template_log(
activity_template_no,
start_time,
end_time,
status,
create_time
) VALUES (
#{activityTemplateNo},
#{startTime},
#{endTime},
#{status},
#{createTime}
)
</insert>
原文链接: https://onlyou.blog.csdn.net//article/details/100691555