MySQL 插入数据后返回自增id的方法

不推荐方法:
INSERT INTO tim_test(`name`)values("tim");
SELECT max(id) from tim_test;
首先性能较低,且在高并发情况下,返回的值是不正确的。

推荐方法:
SELECT LAST_INSERT_ID();
因为LAST_INSERT_ID是基于Connection的,只要每个线程使用独立的Connection对象,LAST_INSERT_ID函数将返回该Connection对AUTO_INCREMENT列最新的insert or update生成的第一个record的ID,这个值不会被其它客户端(Connection)影响,保证了能够找回自己的ID而不影响其它客户端的活动,而且不需要加锁。

注意:
上面有句:insert tim_test(name)values("1"),("2"),("3");批量插入的语句,此时,执行SELECT返回的主键ID是本次连接的第一个插入的主键ID的值,因此是2, 而不是一组列表

MyBatis中MySQL insert返回主键值的方法有两种:
1、 insert按如下修改,主键值包装在了参数对象里边,通过user.getId()获取:
<insert id="insert" parameterType="user" keyProperty="id" useGeneratedKeys="true">
2、 插入selectKey标签,获取同上
<insert id="insert" parameterType="com.mmall.pojo.ApprovalProcess" >
    <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into a (name, type)
    values(#{name}, #{type})
  </insert>

猜你喜欢

转载自blog.csdn.net/timchen525/article/details/80637566