mybatis单条和批量插入返回插入成功后的主键id

单条插入时:

有些时候我们在添加记录成功后希望能直接获取到该记录的主键id值,而不需要再执行一次查询操作。
在使用mybatis作为ORM组件时,可以很方便地达到这个目的。
鉴于mybatis目前已经支持xml配置和注解2种方式,所以分别给予详细介绍。

使用xml配置方式

1.xml配置:

<!-- 插入数据:返回记录的id值 -->
<insert id="insertOneTest" parameterType="org.chench.test.mybatis.model.Test" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
    insert into test(name,descr,url,create_time,update_time) 
    values(#{name},#{descr},#{url},now(),now())
</insert>

2.java代码:

Test test3 = new Test();
//test3.setId(0L);
test3.setName("test6");
test3.setDescr("测试数据6");
test3.setUrl("http://www.aliyun.com.cn");
int rows = sqlSession.insert("org.chench.test.mybatis.mapper.insertOneTest", test3);
sqlSession.commit();
logger.info("insert rows: {}", rows);
// 执行添加记录之后读取POJO的主键id属性
logger.info("insert test id: {}", test3.getId());

3.详细解释
首先,为了在添加记录时能获取到记录主键id,必须在<insert>的xml配置中添加3个属性:

<insert useGeneratedKeys="true" keyProperty="id" keyColumn="id"></insert>

useGeneratedKeys:必须设置为true,否则无法获取到主键id。
keyProperty:设置为POJO对象的主键id属性名称。
keyColumn:设置为数据库记录的主键id字段名称。

其次,新添加主键id并不是在执行添加操作时直接返回的,而是在执行添加操作之后将新添加记录的主键id字段设置为POJO对象的主键id属性。
通过访问POJO对象的主键id属性即可返回。

使用注解方式

详见:http://www.cnblogs.com/nuccch/p/7093843.html 使用mybatis注解实现添加记录时返回主键值


作者:nuccch
出处:http://www.cnblogs.com/nuccch/
声明:本文版权归作者和博客园共有,欢迎转载,但请在文章页面明显位置给出原文连接。

批量插入时:

我们都知道Mybatis在插入单条数据的时候有两种方式返回自增主键:

1、对于支持生成自增主键的数据库:增加 useGenerateKeys和keyProperty ,<insert>标签属性。

2、不支持生成自增主键的数据库:使用<selectKey>。

但是怎么对批量插入数据返回自增主键的解决方式网上看到的还是比较少,至少百度的结果比较少。

Mybatis官网资料提供如下:

First, if your database supports auto-generated key fields (e.g. MySQL and SQL Server), then you can simply set useGeneratedKeys="true" and set the keyProperty to the target property and you're done. For example, if the Authortable above had used an auto-generated column type for the id, the statement would be modified as follows:

<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username,password,email,bio)
  values (#{username},#{password},#{email},#{bio})
</insert>

If your database also supports multi-row insert, you can pass a list or an array of Authors and retrieve the auto-generated keys.

<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username, password, email, bio) values
  <foreach item="item" collection="list" separator=",">
    (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
  </foreach>
</insert>

从官网资料可以看出Mybatis是支持批量插入时返回自增主键的。

但是在本地测试的时候使用上述方式确实不能返回自增id,而且还报错(不认识keyProperty中指定的Id属性),然后在网上找相关资料。终于在Stackoverflow上面找到了一些信息。

解决办法:

1、升级Mybatis版本到3.3.1。官方在这个版本中加入了批量新增返回主键id的功能

2、在Dao中不能使用@param注解。

3、Mapper.xml中使用list变量(parameterType="java.util.List")接受Dao中的参数集合。

下面是具体代码过程,可供参考

mapper.xml层代码

[html]  view plain  copy
  1. <!-- 批量新增 -->  
  2.     <insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id" >  
  3.         INSERT INTO  
  4.         <include refid="t_shop_resource" />  
  5.         (relation_id, summary_id, relation_type)  
  6.         VALUES  
  7.         <foreach collection="list" index="index" item="shopResource" separator=",">  
  8.             (  
  9.                 #{shopResource.relationId}, #{shopResource.summaryId}, #{shopResource.relationType}  
  10.             )  
  11.         </foreach>  
  12.     </insert>  
dao实现层代码
[java]  view plain  copy
  1. public List<ShopResource> batchinsertCallId(List<ShopResource> shopResourceList)  
  2.     {  
  3.         this.getSqlSession().insert(getStatement(SQL_BATCH_INSERT_CALL_ID), shopResourceList);  
  4.         return shopResourceList;// 重点介绍  
  5.     }  

为什么最后返回的参数不是挑用mybatis后的insert的返回值呢,细心的话可以发现,如果使用debug模式观察,会看到调用mybatis后insert的返回值是[],也就是空集合元素,在mybatis3.3.1中,虽然加入了批量新增返回主键id的功能,但是它是这样运行的,在需要新增插入新元素集合对象时,它会需要参数对象,当执行完插入操作后,给之前的参数对象设置id值,也就是改变了需要插入对象集合中的元素的属性id值, 所以接收返回时,返回方法形参参数即可,同样的地址引用改变了内容,返回后的集合也是改变后的集合。

参考地址:


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值