Mybatis自增长id处理

1.使用useGenerateKey

    <insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="personId">
           insert into person(name,pswd) values(#{name},#{pswd})
   </insert> 

或者

   @Mapper
   public interface UserMapper
   {
       @Insert("insert into tbl_user (name, age) values (#{name}, #{age})")
       @Options(useGeneratedKeys=true, keyProperty="userId", keyColumn="user_id")
       void insertUser(User user);
   } 

其中keyProperty对应的属性为返回对象的字段,keyColumn对应的为表字段

返回新增id在新增对象的id属性中

这种只能使用在自增长的数据库中,比如mysql,在oracle中就不行

2.使用select LAST_INSERT_ID()

   <insert id="insert" parameterType="Person">
           <selectKey keyProperty="personId" resultType="long">
               select LAST_INSERT_ID()
           </selectKey>
           insert into person(name,pswd) values(#{name},#{pswd})
   </insert>

LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID会改变。

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

注意:

使用select last_insert_id()时要注意,当一次插入多条记录时,只是获得第一次插入的id值,务必注意。

insert into tb(c1,c2) values (c1value,c2value),(c3value,c4value);select LAST_INSERT_ID();
或者
insert into tb(c1,c2) values (c1value,c2value);
insert into tb(c1,c2) values (c3value,c4value);
select LAST_INSERT_ID();

这两种情况返回的都是最后插入新增的id,就是上文中新增c3value,c4value的id.

3.使用select @@IDENTITY

   <insert id="insert" parameterType="Person">
           <selectKey keyProperty="personId" resultType="long">
               select @@IDENTITY
           </selectKey>
           insert into person(name,pswd) values(#{name},#{pswd})
   </insert>

@@identity是表示的是最近一次向具有identity属性(即自增列)的表插入数据时对应的自增列的值,是系统定义的全局变量。一般系统定义的全局变量都是以@@开头,用户自定义变量以@开头。比如有个表A,它的自增列是id,当向A表插入一行数据后,如果插入数据后自增列的值自动增加至101,则通过select @@identity得到的值就是101。使用@@identity的前提是在进行insert操作后,执行select @@identity的时候连接没有关闭,否则得到的将是NULL值。

4.在MySql中模拟Sequence

这个比较繁琐,有兴趣的可以看[DB][MySql]关于取得自增字段的值、及@@IDENTITY 与并发性问题

参考:

mybatis 操作数据库的主键自增长

mybatis自增长插入id

[DB][MySql]关于取得自增字段的值、及@@IDENTITY 与并发性问题

Mysql 中获取刚插入的自增长id的值

原文地址:https://www.cnblogs.com/hongdada/p/9956992.html