mybatis+mysql 一表主键自增, 插入数据,怎么返回主键。很多人说的都是返回了插入的行数
在标签内 使用
SELECT LAST_INSERT_ID()
SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键
<insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="id">
insert into person(name,pswd) values(#{name},#{pswd})
</insert>
然后用getId()获取主键
<insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="id">
insert into person(name,pswd) values(#{name},#{pswd})
</insert>
然后用getId()获取主键
其实使用SELECT LAST_INSERT_ID()也不一定对,因为如果是多个服务同时访问数据库,同时插入的时候,
SELECT LAST_INSERT_ID()返回的值也是错的,所以最好是使用存储过程的方式,或者在插入前生成
唯一id(guid)的方式来插入会更安全。
selectkey 有一个参数order=before