---
title: "oracle和mysql在ibatis中对自增ID的控制以及MYSQL LAST_INSERT_ID相关说明"
author: "superfofo"
date: "2010-03-18T12:05:05Z"
tags: []
categories: ["企业架构"]
slug: "oracle-mysql-ibatis-id-mysql-last-insert-id"
draft: false
lastmod: "2010-03-18T12:08:20Z"
id: 618892
url: "https://superfofo.iteye.com/blog/618892"
---

sql-map.xml中的代码：(orcale数据库)

<insert id="user.addMember" parameterClass="memberInfo">
    <span style="color:red"><selectKey resultClass="long" type="pre" keyProperty="membId">
    SELECT SEQ_MC_MEMB.nextval AS VALUE FROM DUAL
   </selectKey></span>
     insert into 
     MC_MEMB
     (
     MEMB_ID,MEMB_LOGIN_NAME,MEMB_REAL_NAME,MEMB_TYPE,MEMB_PASSWORD,REG_IP,REG_DATE
     )
     values
     (
     #membId#,#membLoginName:varchar#,
     #membRealName:varchar#,#membType:varchar#,
     #password:varchar#,#regIp:varchar#,#regDate:TIMESTAMP#
     )
</insert>

========================================

daoimpl层的方法：

public Long addMember(Member member) {
  
   Long pk = (Long)getSqlMapClientTemplate().insert("user.addMember",member);
   return pk;
  
}

得到主键。

以上的ibatis配置是oracle，如果数据库为mysql的话应该这样：(mysql数据库)

<insert id="user.addMember" parameterClass="memberInfo">
    <span style="color:red"><selectKey resultClass="long" keyProperty="membId">
        SELECT LAST_INSERT_ID();
   </selectKey></span>
     insert into 
     MC_MEMB
     (
     MEMB_ID,MEMB_LOGIN_NAME,MEMB_REAL_NAME,MEMB_TYPE,MEMB_PASSWORD,REG_IP,REG_DATE
     )
     values
     (
     #<span style="color:red">membId</span>#,#membLoginName:varchar#,
     #membRealName:varchar#,#membType:varchar#,
     #password:varchar#,#regIp:varchar#,#regDate:TIMESTAMP#
     )
</insert>

转帖：*http://hi.baidu.com/mutourenoo/blog/item/63f43035f45f1083a71e121d.html*

以下补充一下自己的使用心得：
mysql与oracle有一点点的区别，oracle中设置sequenceId作为自增的变量，而mysql则通过LAST_INSERT_ID来获取控制这个字段的自增属性。关于LAST_INSERT_ID，有以下的解释：

> 
> 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. 
> 

最后，使用以上的mysql配置，需要对主键设置为自增，否则会在插入的时候出现以下的异常：
SqlMapClient operation; SQL ;   
--- The error occurred in com/dao/ibatis/sqlmap/info_SqlMap.xml.  
--- The error occurred while applying a parameter map.  
--- Check the question_info.insert-InlineParameterMap.  
--- Check the statement (update failed).  
--- Cause: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '0' for key 1; nested exception is com.ibatis.common.jdbc.exception.NestedSQLException:   
--- The error occurred in com/dao/ibatis/sqlmap/info_SqlMap.xml.  
--- The error occurred while applying a parameter map.  
--- Check the question_info.insert-InlineParameterMap.  
--- Check the statement (update failed).  
--- Cause: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '0' for key 1
Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '0' for key 1