关于在iBatis中配置Oracle以及MySQL 自增字段

 <insert id="insertPerson" parameterClass="person">
		<!--	     MySQL数据库自增字段的控制       -->
	  	<selectKey resultClass="int" keyProperty="id">
	  		 SELECT LAST_INSERT_ID(); 
	  	</selectKey>
	  	<!--	    oracle数据库自增字段的控制       -->
	  	<selectKey resultClass="int" keyProperty="id">
	  		select seq_person.nextval as id from dual;
	  	</selectKey>
	  
	     insert into t_person(
	     	id,
	     	name,
	     	age
	     )
	     values(
	     	#id#,
	     	#name#,
	     	#age#
	     )
</insert>

  

注意:

LAST_INSERT_ID 是与table无关的。
1、如果向表a插入多条数据后,LAST_INSERT_ID返回的是第一条插入的record的Id;
2、如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID就会改变。

一般情况下获取刚插入的数据的id,使用select max(id) from table 是可以的。
但在多线程情况下,就不行了。在多用户交替插入数据的情况下max(id),显然不能用。
如:
用户a插入后,用户b插入,此时用户a旨在获取刚刚用户a插入的自增id,但此时却因为用户b对该自增id进行了操作而通过通过max(id)获取了此时b已操作过的自增id。

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

查看LAST_INSERT_ID相关说明如下:
自动返回最后一个 INSERT 或 UPDATE 操作为 AUTO_INCREMENT 列设置的第一个发生的值。
The ID that was generated is maintained in the server on a per-connection basis.
Important: If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only.

原文地址:https://www.cnblogs.com/E-star/p/3438755.html