【Ibatis】(七)、自动生成主键

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

1. 建表,将id设置为主键,且需加上auto_increment设置为自动增加

create table ibatis_db.t_product(pro_id int(6)  

PRIMARY KEY auto_increment   not null,

pro_description varchar(150) not null,

pro_price double not null);

 

2.product_sqlmap.xml中将

Xml代码   收藏代码
  1. <insert id="insertProduct"  
  2.          parameterClass="product">  
  3.          <![CDATA[ 
  4.              insert into t_product(prd_id,prd_description,prd_price)  
  5.                          values(#id#,#description#,#price#) 
  6.         ]]>  
  7. </insert>  

 修改为:

Xml代码   收藏代码
  1. <!-- <span style="color: #ff0000;">Oracle SEQUENCE Example</span> 
  2.  
  3. -->  
  4. <insert id="insertProduct-ORACLE" parameterClass="com.domain.Product">  
  5.         <selectKey resultClass="int" keyProperty="id" >  
  6.                 SELECT STOCKIDSEQUENCE.NEXTVAL AS ID FROM DUAL  
  7.         </selectKey>  
  8.         insert into T_PRODUCT (PRD_ID,PRD_DESCRIPTION)  
  9.         values (#id#,#description#)  
  10. </insert>  
  11.   
  12. <!--<span style="color: #ff0000;">Microsoft SQL Server IDENTITY Column Example</span> 
  13.  
  14. -->  
  15. <insert id="insertProduct-MS-SQL" parameterClass="com.domain.Product">  
  16.         insert into T_PRODUCT (PRD_DESCRIPTION)  
  17.         values (#description#)  
  18.         <selectKey resultClass="int" keyProperty="id" >  
  19.                 SELECT @@IDENTITY AS ID  
  20.         </selectKey>  
  21. </insert>  
  22.   
  23.   
  24. <!--<span style="color: #ff0000;">My sql SEQUENCE</span> 
  25. -->  
  26. <insert id="insertUser-MY-SQL" parameterClass="product">  
  27.     INSERT   INTO   T_PRODUCT  (pro_description, pro_price) VALUES (#description#,#price#)                         
  28.     <selectKey   resultClass="int"   keyProperty="id">  
  29.          SELECT   LAST_INSERT_ID() as id                        
  30.     </selectKey>  
  31. </insert><span style="color: #000000;">  
  32. </span>  
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值