向数据库插入一条数据同时获取主键id

首先创建一个对象

将这个对象使用mybatis插入数据库

java 复制代码
Student stu = new Student(null, "stu", 18, null);
mapper.insertEntity(stu);
System.out.println(stu);
复制代码
在mapper.xml文件中开启配置之后输出传入的stu对象就会有主键id回传
XML 复制代码
<!-- 插入语句示例  int insertEntity(Student student);
    useGeneratedKeys="true" 表示当前标签中要执行的sql使用了自动递增主键
    keyProperty="studentId" 表示把自动递增的主键的值 放入 方法中传输过来参数中的某一个属性中 (放入了student studentId属性中)
-->
<insert id="insertEntity" useGeneratedKeys="true" keyProperty="studentId">
    insert into student(`student_id`,`student_name`,`student_age`,`student_image`)
    values (#{studentId},#{studentName},#{studentAge},#{studentImage});
</insert>
相关推荐
Yeats_Liao32 分钟前
物联网平台MongoDB实战|(一)为什么选择MongoDB
数据库·物联网·mongodb
ZhengEnCi1 小时前
覆盖索引是什么:用借书和外卖看懂回表这件事
sql·mysql·postgresql
鹤落晴春1 小时前
MySQL日志梳理
运维·数据库·mysql
jaysee-sjc1 小时前
【黑马点评】Day02:优惠券秒杀与分布式锁
java·分布式·nginx·spring·node.js·tomcat·maven
五彩小白2 小时前
Redis的过期删除和内存淘汰机制
数据库·redis·缓存
学长毕设2 小时前
基于SpringBoot 博物馆文物租赁及修复管理系统-附源码
大数据·数据库·spring boot
秋天的怀念_David2 小时前
算法一千零一夜 · 第三十五夜 · 恢复风暴
java·程序人生·算法
考虑考虑2 小时前
JDK27中的加密对象的 PEM 编码
java·后端·java ee
apcipot_rain2 小时前
C++转Java日记(14)
数据库
行者-全栈开发3 小时前
SpringBoot + GraalVM 原生编译实战:启动时间从8秒到0.5秒的极致优化
java·spring boot·后端