iBatis的sqlMap配置文件的selectKey元素有个type属性,可以指定pre或者post表示前生成(pre)还是后生成(post)。
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>
<!-- 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">
- <selectKey resultClass="int" keyProperty="id">
- <![CDATA[insert into PRODUCT (PRD_DESCRIPTION) values(#description#)
- SELECT SCOPE_IDENTITY() AS ID ]]>
- </selectKey>
- </insert>
<!-- 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 -->
- lt;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>
- lt;/insert>
<!-- 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>
当然mysql中可以用auto_increment!ms sql中也有identity可以用,这样做是为了兼容其他数据库!