本文转载于:http://www.iteye.com/topic/215571
从网上搜索了一些mybatis自动生成主键的内容,拷贝以备以后方便使用:
 
 
Oracle设置:
<!-- Oracle SEQUENCE -->    
<insert id="insertProduct-ORACLE" parameterClass="com.domain.Product">    
        <selectKey resultClass="int" keyProperty="id" type="pre">    
                <![CDATA[SELECT STOCKIDSEQUENCE.NEXTVAL AS ID FROM DUAL]]>    
        </selectKey>    
        <![CDATA[insert into PRODUCT (PRD_ID,PRD_DESCRIPTION) values(#id#,#description#)]]>    
</insert>
 
MS SQL Server配置:
 
<!-- Microsoft SQL Server IDENTITY Column -->    
<insert id="insertProduct-MS-SQL" parameterClass="com.domain.Product">    
        <![CDATA[insert into PRODUCT (PRD_DESCRIPTION) values(#description#) ]]>    
        <selectKey resultClass="int" keyProperty="id" type="post">    
                <![CDATA[SELECT @@IDENTITY AS ID ]]>
                <!-- 该方法不安全 应当用SCOPE_IDENTITY() 但这个函数属于域函数,需要在一个语句块中执行。 -->
        </selectKey>    
</insert>
 
上述MS SQL Server配置随是官网提供的配置,但实际上却恰恰隐患重重!按下述配置,确保获得有效主键。
<!-- Microsoft SQL Server IDENTITY Column 改进-->    
<insert id="insertProduct-MS-SQL" parameterClass="com.domain.Product">    
        <selectKey resultClass="int" keyProperty="id">    
                <![CDATA[insert into PRODUCT (PRD_DESCRIPTION) values(#description#)
                SELECT SCOPE_IDENTITY() AS ID ]]>
        </selectKey>    
</insert>
 
MySQL配置
<!-- MySQL Last Insert Id -->
<insert id="insertProduct-Mysql" parameterClass="com.domain.Product">
        <![CDATA[insert into PRODUCT(PRD_DESCRIPTION) values(#description#)]]>    
        <selectKey resultClass="int" keyProperty="id">
                <![CDATA[SELECT LAST_INSERT_ID() AS ID ]]>    
                <!-- 该方法LAST_INSERT_ID()与数据库连接绑定,同属统一会话级别,不会发生上述MS SQL Server的函数问题。 -->
        </selectKey>
</insert>