前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Mybatis插入数据后返回主键id

Mybatis插入数据后返回主键id

作者头像
欠扁的小篮子
发布2018-07-04 16:22:35
2K0
发布2018-07-04 16:22:35
举报

有时候使用mybatis插入数据后,需要用到记录在数据库中的自增id,可以利用keyProperty来返回,赋值给实体类中的指定字段。

单条记录插入并返回

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> 
添加useGeneratedKeys="true" 以及keyProperty="id"即可。id为实体类中的字段名称

多条记录插入并返回

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>  

坑:要注意,多条记录时,有可能会出现id没有返回的情况。检查以下几点:

1、Mybatis版本3.3.1及其以上。

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

3、Mapper.xml中使用list变量接受Dao中的集合。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-06-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 单条记录插入并返回
  • 多条记录插入并返回
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档