广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Mybatis插入时返回自增主键方式(selectKey和useGeneratedKeys)
  • 685
分享到

Mybatis插入时返回自增主键方式(selectKey和useGeneratedKeys)

2024-04-02 19:04:59 685人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录mybatis插入时返回自增主键Mybatis批量插入返回自增主键解决办法Mybatis插入时返回自增主键 通过selectKey在插入操作前或者操作后获取key值,做

Mybatis插入时返回自增主键

通过selectKey在插入操作前或者操作后获取key值,做为字段插入或返回字段。(此段代码获取的序列值id作为字段值插入到实体类中返回)


<insert id="insert">
 <selecTKEy keyProperty="id" resultType="int" order="AFTER">
  SELECT id FROM myTable
 </selectKey> 
 INSERT INTO myTable VALUES(#{id}, #{name})
</insert>

useGeneratedKeys

如果数据库支持自增长主键字段(比如MysqlSQL Server)设置useGeneratedKeys=”true”和keyProperty="Id",id 是表的主键名,这样就可以插入主键id值

oracle则不支持自增长id,设置useGeneratedKey=”false”,如果设置true则会有报错信息。通过nextval函数,如SEQ_table.Nextval生成id


<insert id="addCover" parameterType="java.util.Map" useGeneratedKeys="true" keyProperty="Id">
 insert into cover(title,path,update_time)
 values(#{title},#{path},#{update_time}) 
</insert> 

int addCover(Map<String,Object> map);

Mybatis批量插入返回自增主键

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

1、对于支持生成自增主键的数据库:useGenerateKeys和keyProperty。

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。

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

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Mybatis插入时返回自增主键方式(selectKey和useGeneratedKeys)

本文链接: https://www.lsjlt.com/news/136539.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作