首页 技术 正文
技术 2022年11月21日
0 收藏 487 点赞 4,639 浏览 1214 个字

我们都知道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 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 

 <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中的集合。

参考地址:

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,944
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,470
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,284
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,100
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,730
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,766