Mybatis+Mysql插入数据库返回自增主键id值的三种方法

 

一、场景:

插入数据库的值需要立即得到返回的主键id进行下一步程序操作

 

二、解决方法:

第一种:使用通用mapper的插入方法

Mapper.insertSelective(record);

此方法:插入一条数据,只插入不为null的字段,不会影响有默认值的字段
支持Oracle序列,UUID,类似Mysql的INDENTITY自动增长(自动回写)
优先使用传入的参数值,参数值空时,才会使用序列、UUID,自动增长


controller的实际应用:使用方法id会直接将映射到参数的实体上使用时直接使用参数的实体get获取值

 

通用mapper相关配置查看其它文章   http://blog.csdn.net/isea533/article/details/41457529

 

第二种:编写sql语句

dao层方法:

[java] view plain copy
 
  1. /** 
  2.      * 插入数据库并返回主键id 
  3.      * @param batch 
  4.      * @return 
  5.      */  
  6.     Integer insertBatchReturnId(Batch batch);  

 

xml的sql语句写法

记得加上useGeneratedKeys和keyProperty配置即可,前者是指设置是否使用jdbc的getGenereatedKeys方法获取主键并赋值到keyProperty设置的属性中,后者即实体类主键字段(并且大小写要对应上)

 

[html] view plain copy
 
  1. <insert id="insertBatchReturnId" useGeneratedKeys="true" keyProperty="id" parameterType="org.uz.dxt.model.bankbase.Batch"  >    
  2.        
  3.     insert into t_batch (  
  4.     batchCode,  
  5.     bankCode,  
  6.     bizType,  
  7.     companyCode,  
  8.     wtEndDate,  
  9.     wtDate,  
  10.     contractId,   
  11.     totalCount,  
  12.     totalBase,   
  13.     handCode)  
  14.     values   
  15.     ( #{batchcode},  
  16.     #{bankcode},  
  17.     #{biztype},  
  18.     #{companycode},  
  19.     #{wtenddate},  
  20.     #{wtdate},   
  21.     #{contractid},  
  22.     #{totalcount},  
  23.     #{totalbase},   
  24.     #{handCode})  
  25. </insert>    

 

 

controller的实际应用:使用方法id会直接将映射到参数的实体上使用时直接使用参数的实体get获取值

 

[java] view plain copy
 
  1. batchService.insertBatch(param);//实体  
  2. idlist.add(param.getId());  

第三种:sql语句使用<selectKey>获取自增逐渐id


 

 

[html] view plain copy
 
  1. <insert id="add" parameterType="EStudent">  
  2.   // 下面是SQLServer获取最近一次插入记录的主键值的方式  
  3.   <selectKey resultType="_long" keyProperty="id" order="AFTER">  
  4.     select @@IDENTITY as id  
  5.   </selectKey>  
  6.   insert into TStudent(name, age) values(#{name}, #{age})  
  7. </insert>  

使用用法同上

 

 

这里推荐使用第一种和第二种中方法

第三种方法对oracl额外的配置

 

 

controller的实际应用:使用方法id会直接将映射到参数的实体上使用时直接使用参数的实体get获取值
posted @ 2018-03-21 12:19  小黑妹007  阅读(45857)  评论(1编辑  收藏  举报