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层方法:

/**
	 * 插入数据库并返回主键id
	 * @param batch
	 * @return
	 */
	Integer insertBatchReturnId(Batch batch);

xml的sql语句写法

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

	<insert id="insertBatchReturnId" useGeneratedKeys="true" keyProperty="id" parameterType="org.uz.dxt.model.bankbase.Batch"  >  
		 
	   	insert into t_batch (
		batchCode,
		bankCode,
		bizType,
		companyCode,
		wtEndDate,
		wtDate,
		contractId, 
		totalCount,
		totalBase, 
		handCode)
		values 
		( #{batchcode},
		#{bankcode},
		#{biztype},
		#{companycode},
		#{wtenddate},
		#{wtdate}, 
		#{contractid},
		#{totalcount},
		#{totalbase}, 
		#{handCode})
	</insert>  


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

batchService.insertBatch(param);//实体
idlist.add(param.getId());

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


<insert id="add" parameterType="EStudent">
  // 下面是SQLServer获取最近一次插入记录的主键值的方式
  <selectKey resultType="_long" keyProperty="id" order="AFTER">
    select @@IDENTITY as id
  </selectKey>
  insert into TStudent(name, age) values(#{name}, #{age})
</insert>

使用用法同上


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

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



controller的实际应用:使用方法id会直接将映射到参数的实体上使用时直接使用参数的实体get获取值
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值