ibatis主键生成策略

时间:2023-02-10 00:43:46

iBatis的sqlMap配置文件的selectKey元素有个type属性,可以指定pre或者post表示前生成(pre)还是后生成(post)。

Oracle设置

Java代码 ibatis主键生成策略 ibatis主键生成策略ibatis主键生成策略
  1. <!-- Oracle SEQUENCE -->
  2. <insert id="insertProduct-ORACLE" parameterClass="com.domain.Product">
  3. <selectKey resultClass="int" keyProperty="id" type="pre">
  4. <![CDATA[SELECT STOCKIDSEQUENCE.NEXTVAL AS ID FROM DUAL]]>
  5. </selectKey>
  6. <![CDATA[insert into PRODUCT (PRD_ID,PRD_DESCRIPTION) values(#id#,#description#)]]>
  7. </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配置
Java代码 ibatis主键生成策略 ibatis主键生成策略ibatis主键生成策略
  1. <!-- Microsoft SQL Server IDENTITY Column 改进-->
  2. <insert id="insertProduct-MS-SQL" parameterClass="com.domain.Product">
  3. <selectKey resultClass="int" keyProperty="id">
  4. <![CDATA[insert into PRODUCT (PRD_DESCRIPTION) values(#description#)
  5. SELECT SCOPE_IDENTITY() AS ID ]]>
  6. </selectKey>
  7. </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配置
Java代码 ibatis主键生成策略 ibatis主键生成策略ibatis主键生成策略
  1. <!-- MySQL Last Insert Id -->
  2. lt;insert id="insertProduct-Mysql" parameterClass="com.domain.Product">
  3. <![CDATA[insert into PRODUCT(PRD_DESCRIPTION) values(#description#)]]>
  4. <selectKey resultClass="int" keyProperty="id">
  5. <![CDATA[SELECT LAST_INSERT_ID() AS ID ]]>
  6. <!-- 该方法LAST_INSERT_ID()与数据库连接绑定,同属统一会话级别,不会发生上述MS SQL Server的函数问题。 -->
  7. </selectKey>
  8. 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可以用,这样做是为了兼容其他数据库!