对于任何数据库来说,提供唯一标识数据表中一行记录的能力是至关重要的。几乎所有数据库都提供了为新添加的行自动生成主键的方法。这样再操作数据库的时候比较方便,但它也带来了一个问题,如果我们需要知道新生成的主键值该怎么办?
有的数据库供应商是预先生成(pre-generate)主键的(如Oracle和PostgreSQL),有的则是事后生成(post-generate)的(如SQL Server和MySQL)。不管是哪种方式,我们都可以使用<selectKey>节点来获取<insert>语句所产生的主键。下面的例子演示了这两种方式下的做法:
<!--OracleSEQUENCEExampleusing.NET1.1System.Data.OracleClient-->
<insertid="insertProduct-ORACLE"parameterClass="product">
<selectKeyresultClass="int"type="pre"property="Id">
SELECTSTOCKIDSEQUENCE.NEXTVALASVALUEFROMDUAL
</selectKey>
insertintoPRODUCT(PRD_ID,PRD_DESCRIPTION)values(#id#,#description#)
</insert>
<!--MicrosoftSQLServerIDENTITYColumnExample-->
<insertid="insertProduct-MS-SQL"parameterClass="product">
insertintoPRODUCT(PRD_DESCRIPTION)
values(#description#)
<selectKeyresultClass="int"type="post"property="id">
select@@IDENTITYasvalue
</selectKey>
</insert>
<!--MySQLExample-->
<insertid="insertProduct-MYSQL"parameterClass="product">
insertintoPRODUCT(PRD_DESCRIPTION)
values(#description#)
<selectKeyresultClass="int"type="post"property="id">
selectLAST_INSERT_ID()asvalue
</selectKey>
</insert>
本文介绍了在不同数据库系统中如何使用<selectKey>节点来获取新插入记录的主键值。通过Oracle、SQL Server及MySQL的具体示例,展示了预生成和后生成主键的方法。
191

被折叠的 条评论
为什么被折叠?



