MyBatis与IBatis插入返回主键

本文介绍了使用MyBatis框架时如何配置返回插入记录的主键值,包括针对Sequence主键和自增主键的不同配置方式。
MyBatis与IBatis插入返回主键

一、MyBatis插入返回主键

在使用MyBatis做持久层时,insert语句默认是不返回记录的主键值,而是返回插入的记录条数;如果业务层需要得到记录的主键时,可以通过配置的方式来完成这个功能。 
针对Sequence主键而言,在执行insert sql前必须指定一个主键值给要插入的记录,如Oracle、DB2,可以采用如下配置方式:

 

[html]  view plain  copy
 
  1. <insert id="addOracle" parameterType="Student">  
  2.         <selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id">    
  3.             select seq_t_student .nextval from dual    
  4.         </selectKey>   
  5.         insert into t_student(id,name)  
  6.         values(#{id},#{name})  
  7. </insert>  
  8.       

针对自增主键的表,在插入时不需要主键,而是在插入过程自动获取一个自增的主键,比如MySQL,可以采用如下两种配置方式:

 

1.返回主键方式

[html]  view plain  copy
 
  1. <insert id="add" parameterType="Student">  
  2.         <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">    
  3.             SELECT LAST_INSERT_ID() AS id    
  4.         </selectKey>    
  5.           
  6.         insert into t_student(name)  
  7.         values(#{name})  
  8. </insert>  

2.设置useGeneratedKeys="true"属性方式

 

 

[html]  view plain  copy
 
  1. <insert id="add1" parameterType="Student"  useGeneratedKeys="true" keyProperty="id">    
  2.         insert into t_student(name)  
  3.         values(#{name})  
  4. </insert>  

转载于:https://my.oschina.net/xiaominmin/blog/1598295

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值