Mybatis实现插入数据后返回主键过程解析
作者:_dafeng 时间:2022-07-14 18:43:15
添加记录后获取主键ID,这是一个很常见的需求,特别是在一次前端调用中需要插入多个表的场景。
除了添加单条记录时获取主键值,有时候可能需要获取批量添加记录时各记录的主键值,MyBatis从3.3.1版本开始支持批量添加记录并返回各记录主键字段值。
一、获取新添加记录主键字段值
注意: 在MyBatis中添加操作返回的是记录数并非记录主键id。
如果需要获取新添加记录的主键值,需要在执行添加操作之后,直接读取Java对象的主键属性。
Integer rows = sqlSession.getMapper(UserMapper.class).insertUser(user);
System.out.println("rows = " + rows); // 添加操作返回记录数
System.out.println("id = " + user.getId()); // 执行添加操作之后通过Java对象获取主键属性值
二、在映射器中配置获取记录主键值
1.xml映射器
在定义xml映射器时设置属性useGeneratedKeys值为true,并分别指定属性keyProperty和keyColumn为对应的数据库记录主键字段与Java对象的主键属性。
1.1 插入单条记录
<mapper namespace="com.dafeng.dao.mapper">
<!-- 插入数据:返回记录主键id值 -->
<insert id="insertUser" parameterType="com.dafeng.model.User" useGeneratedKeys="true" keyProperty="id" keyColumn="id" >
insert into user(name,age,create_time,update_time) values(#{name},#{age},now(),now())
</insert>
</mapper>
1.2 插入多条记录
<!-- 批量添加数据,并返回主键字段 -->
<insert id="insertBatchUser" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(name,age,create_time,update_time) VALUES
<foreach collection="list" separator="," item="u">
(#{u.name},#{u.age},now(),now())
</foreach>
</insert>
2.接口映射器
在接口映射器中通过注解@Options分别设置参数useGeneratedKeys,keyProperty,keyColumn值
2.1 插入单条记录
// 返回主键字段id值
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Insert("insert into user(name,age,create_time,update_time) values(#{name},#{age},now(),now())")
Integer insertUser(User user);
2.2 插入多条记录
如果希望执行批量添加并返回各记录主键字段值,只能在xml映射器中实现,在接口映射器中无法做到。
来源:https://www.cnblogs.com/dafengdeai/p/12960987.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SpringBoot2之PUT请求接收不了参数的解决方案
![](https://img.aspxhome.com/file/2023/2/58202_0s.png)
Java 线程池ExecutorService详解及实例代码
C++实现LeetCode(5.最长回文子串)
使用Springboot对配置文件中的敏感信息加密
![](https://img.aspxhome.com/file/2023/0/64020_0s.jpg)
JavaWeb开发使用Cookie创建-获取-持久化、自动登录、购物记录、作用路径
![](https://img.aspxhome.com/file/2023/2/64902_0s.png)
解决问题:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources
![](https://img.aspxhome.com/file/2023/1/59871_0s.jpg)
Java使用备忘录模式实现过关类游戏功能详解
![](https://img.aspxhome.com/file/2023/2/60782_0s.png)
Android SharedPreferences存储用法详解
![](https://img.aspxhome.com/file/2023/8/83528_0s.gif)
解读java try catch 异常后还会继续执行吗
![](https://img.aspxhome.com/file/2023/7/66677_0s.png)
记一次公司JVM堆溢出抽丝剥茧定位的过程解析
![](https://img.aspxhome.com/file/2023/7/59007_0s.jpg)
SpringBoot整合Security安全框架实现控制权限
![](https://img.aspxhome.com/file/2023/3/65583_0s.png)
Java对象类型的判断详解
SpringBoot项目多数据源及mybatis 驼峰失效的问题解决方法
基于Flutter实现图片选择和图片上传
![](https://img.aspxhome.com/file/2023/1/106021_0s.jpg)
java @Value(
![](https://img.aspxhome.com/file/2023/7/63017_0s.png)
详解如何在SpringBoot中自定义参数解析器
JAVA内存模型(JMM)详解
![](https://img.aspxhome.com/file/2023/5/59975_0s.png)
Android之使用Bundle进行IPC详解
使用Jitpack发布开源Java库的详细流程
![](https://img.aspxhome.com/file/2023/5/63395_0s.png)