zoukankan      html  css  js  c++  java
  • 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>

  • 相关阅读:
    ubuntu video and audio
    js type
    jumpserver 堡垒机环境搭建
    ubuntu dnsmasq
    bind--dns-docker---[nslookup/dig]
    java maven scope compile,provide,system,test,runtime
    docker install and minikube install
    nginx break-circus orange api-gateway
    一个IP能建立的最大连接数是多少?
    Docker 在6.4上安装
  • 原文地址:https://www.cnblogs.com/xianz666/p/14887924.html
Copyright © 2011-2022 走看看