向数据库插入一条数据同时获取主键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>
相关推荐
鹤望兰6752 分钟前
字节跳动国际支付-后端开发-三面面经
java
Flittly9 分钟前
【AgentScope Java新手村系列】(14)人机交互
java·spring boot·spring
RainCity14 分钟前
Java Swing 自定义组件库分享(十二)
java·笔记·后端
xiezhr2 小时前
逛GitHub发现了一款免费的带AI功能的数据库管理工具
数据库·ai编程·dba
吃饱了得干活16 小时前
Spring Cloud Gateway 微服务网关:路由、断言、过滤器
java·spring cloud
lwx5728018 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端
Flynt19 小时前
从Spring Boot 4.0升到4.1,我在Maven和gRPC上栽了跟头
java·spring boot·后端
plainGeekDev20 小时前
Activity 间传值 → Navigation 参数
android·java·kotlin
plainGeekDev20 小时前
onActivityResult → ActivityResult API
android·java·kotlin
Sunia20 小时前
《AgentX 专栏》10-生产部署:3台2C4G云服务器把企业级Agent真正跑起来的完整方案
java·架构