很多数据库支持自动生成主键的数据类型。不过这通常(并不总是)是个私有的特性。SQL Map通过<insert>的子元素<selectKey>来支持自动生成的键值。它同时支持预生成(如Oracle)和后生成两种类型(如MS-SQL Server)。
1. 建表,将id设置为主键,且需加上auto_increment设置为自动增加
create table ibatis_db.t_product(pro_id int(6)
PRIMARY KEYauto_incrementnot null,
pro_descriptionvarchar(150) not null,
pro_price double not null);
2.product_sqlmap.xml中将
- <insertid="insertProduct"
- parameterClass="product">
- <![CDATA[
- insertintot_product(prd_id,prd_description,prd_price)
- values(#id#,#description#,#price#)
- ]]>
- </insert>
修改为:
- <!--<spanstyle="color:#ff0000;">OracleSEQUENCEExample</span>
- -->
- <insertid="insertProduct-ORACLE"parameterClass="com.domain.Product">
- <selectKeyresultClass="int"keyProperty="id">
- SELECTSTOCKIDSEQUENCE.NEXTVALASIDFROMDUAL
- </selectKey>
- insertintoT_PRODUCT(PRD_ID,PRD_DESCRIPTION)
- values(#id#,#description#)
- </insert>
- <!--<spanstyle="color:#ff0000;">MicrosoftSQLServerIDENTITYColumnExample</span>
- -->
- <insertid="insertProduct-MS-SQL"parameterClass="com.domain.Product">
- insertintoT_PRODUCT(PRD_DESCRIPTION)
- values(#description#)
- <selectKeyresultClass="int"keyProperty="id">
- SELECT@@IDENTITYASID
- </selectKey>
- </insert>
- <!--<spanstyle="color:#ff0000;">MysqlSEQUENCE</span>
- -->
- <insertid="insertUser-MY-SQL"parameterClass="product">
- INSERTINTOT_PRODUCT(pro_description,pro_price)VALUES(#description#,#price#)
- <selectKeyresultClass="int"keyProperty="id">
- SELECTLAST_INSERT_ID()asid
- </selectKey>
- </insert><spanstyle="color:#000000;">
- </span>