首页 > 技术 > iBatis中得到数据库自动生成值的方法

iBatis中得到数据库自动生成值的方法

iBatis使用SqlMapClient.insert()执行插入语句,这个方法返回一个Object,代表插入的主键值。但如果想得到这个值,必须在<insert>元素中进行另外的配置。在iBatis中文文档的20页中有提到,也可以直接搜索”selectKey”。

主键值的获取支持两种方式,前获取和后获取,如中文文档中例子写的那样。前获取需要把selectkey元素放在前面,后获取反之。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--Oracle SEQUENCE Example --> 
<insert id="insertProduct-ORACLE" parameterClass="com.domain.Product"> 
    <selectKey resultClass="int" keyProperty="id" > 
        SELECT STOCKIDSEQUENCE.NEXTVAL AS ID FROM DUAL 
    </selectKey> 
    insert into PRODUCT (PRD_ID,PRD_DESCRIPTION)  values (#id#,#description#) 
</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>

DB2的资料比较少,我试了很多次才搞出来,类似于SQL Server,对于使用了IDENTITY的Column:

1
2
3
4
5
6
<insert id="insertProduct" parameterClass="com.domain.Product">
	INSERT INTO PRODUCT  (PRD_DESCRIPTION) VALUES (#description#)
	<selectKey resultClass="int" keyProperty="id">
		SELECT distinct IDENTITY_VAL_LOCAL()  AS ID FROM PRODUCT 
	</selectKey>
</insert>

keyProperty属性必须对应于SQL语句中SELECT出来的Column Alias,在本例中均为“id”

分类: 技术 标签:
  1. 沫沫
    2009年7月10日20:52 | #1

    小白说:不许写我看不懂的技术blog;
    小黑小声说:那我就换个域名,重新开垦一个纯技术的blog;

    [回复]

  1. 本文目前尚无任何 trackbacks 和 pingbacks.

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word