Mybatis[批量]插入返回自增ID

简介

最近在业务功能中需要获取mybatis插入的数据并且返回插入数据的ID,去执行其他的操作,说来也很简单,在正常的insert标签里面加入提供的其他属性即可实现,故现在抽时间整理出来,希望能帮助到需要帮助的朋友

环境

数据库:mysql(table的id字段设置为自增)
依赖:jar

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.2.7</version>
</dependency>

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.2.2</version>
</dependency>

单条插入返回

DaoMapper接口

Mapper.xml配置

<insert id="insert" useGeneratedKeys="true" keyProperty="releaseDetailsId"   
parameterType="com.xxx.CmsReleaseDetails" >
insert into cms_release_details (RELEASE_DETAILS_ID, RELEASE_DETAILS_CODE
)
values (#{releaseDetailsId,jdbcType=INTEGER}, #{releaseDetailsCode,jdbcType=VARCHAR}
)
  </insert>

总结:即在普通插入中加入useGeneratedKeys和keyProperty属性即可,在插入完成后直接获取该插入实体封装的ID即可获取到参数。

批量插入

批量插入DaoMapper接口
<insert id="insertBatch" useGeneratedKeys="true" 
keyProperty="releaseDetailsId" keyColumn="RELEASE_DETAILS_ID" 
parameterType="java.util.List" >
  insert into cms_release_details ( 
  RELEASE_DETAILS_ID,RELEASE_DETAILS_CODE) values 
  <foreach collection="list" item="item" index="index" separator="," > 
  ( #{item.releaseDetailsId,jdbcType=INTEGER},
#{item.releaseDetailsCode,jdbcType=VARCHAR}) 
      </foreach>
 </insert>

但此时插入却报异常:

nested exception is org.apache.ibatis.binding.BindingException:
 Parameter ' releaseDetailsId ' not found. 
Available parameters are [list, collection]

后查证资料,批量插入返回ID报错bug在mybatis.3.3.1才被修复,故将mybatis升级为3.3.1,spring-mybatis版本不做处理,重启后正常插入且成功返回正确id

总结

其实批量插入返回ID和单条插入返回ID没有什么差别,首先还是要确定原本不返回值的插入是否成功,然后再做进一步操作,循序渐进

参考资料:

https://github.com/mybatis/mybatis-3/pull/324
https://github.com/abel533/mybatis-3/blob/master/src/main/java/org/apache/ibatis/executor/keygen/Jdbc3KeyGenerator.java

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 4,598评论 0 4
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 132,332评论 18 139
  • 从出生开始你就常常睡觉的时候嘴角带微笑,我奇怪这么小的孩子就会笑了,姥姥说你那是在做故事。 两个月的时候,赶上情人...
    毛毛虫的夏天1213阅读 424评论 0 0
  • 某位年轻的校友虚心讨教去西安的攻略,引起了我记一篇流水账的想法。旅行途中的种种,新奇喜悦悲伤疲惫烦躁,都是难得的独...
    张企鹅阅读 103评论 0 0