標籤:des http io ar os sp strong 檔案 資料
iBatis的sqlMap設定檔的selectKey元素有個type屬性,可以指定pre或者post表示前產生(pre)還是後產生(post)。
Oracle設定
Xml代碼
- <!-- 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配置
Xml代碼
- <!-- 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配置隨是官網提供的配置,但實際上卻恰恰隱患重重!按下述配置,確保獲得有效主鍵。
Xml代碼
- <!-- 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配置
Xml代碼
- <!-- 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>
通過以上方式,可以最大程度上確保插入資料的時候獲得當前自增主鍵。
iBatis自動產生的主鍵 (Oracle,MS Sql Server,MySQL)【轉】