iBatis自动生成的主键 返回主键 (Oracle,Sql Server,Mysql,SQLite)

时间:2021-06-02 21:39:05

iBatis自动生成的主键


很多数据库支持自动生成主键的数据类型。不过这通常(并不总是)是个私有的特性。
SQL Map 通过<insert>的子元素<selectKey>来支持自动生成的键值。它同时支持预生成(如
Oracle)和后生成两种类型(如 MS-SQL Server)。下面是两个例子:


< !—Oracle SEQUENCE Example -->

<insert id="insertProduct-ORACLE" parameterClass="com.domain.Product">  
insert into PRODUCT (PRD_ID,PRD_DESCRIPTION)
values (#id#,#description#)
<selectKey resultClass="int" keyProperty="id">
SELECT STOCKIDSEQUENCE.NEXTVAL AS ID FROM DUAL
</selectKey>
</insert>


<!— Microsoft SQL Server IDENTITY Column Example -->

<insert id="insertProduct-MS-SQL" parameterClass="com.domain.Product"> 
insert into PRODUCT (PRD_DESCRIPTION)
values (#description#)
<selectKey resultClass="int" keyProperty="id" >
SELECT @@IDENTITY AS ID
</selectKey>
</insert>



<!-- Mysql Auto Increased ID-->

<insert id="insertProduct-Mysql" parameterClass="com.domain.Product">
insert into PRODUCT(PRD_DESCRIPTION)
values (#description#)
<selectKey resultClass="int" keyProperty="id">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>


<!-- SQLite-->

<insert id="Create" parameterClass="Subject">
INSERT INTO SUBJECT
(SubjectName,QuestionCount,IsNowPaper)
VALUES(#SubjectName#,#QuestionCount#,#IsNowPaper#)
<selectKey resultClass="int" type="post" property="SubjectId">
SELECT seq
FROM sqlite_sequence
WHERE (name = 'SUBJECT')
</selectKey>
</insert>
注意:name = 'SUBJECT'中SUBJECT为表名称