向数据库插入一条数据同时获取主键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>
相关推荐
BullSmall1 小时前
PostgreSQL 14 pg_dumpall 完整备份指南
数据库·postgresql·oracle
AI多Agent协作实战派2 小时前
AI多Agent协作系统实战(十七):凌晨4点,我的AI系统在“假装工作“——3个bug同时爆炸的5小时
java·前端·bug
gaolei_eit2 小时前
Java+Ai+vue
java·spring·maven
qq_2518364572 小时前
基于java Web 动漫视频网站毕业论文
java·开发语言·前端
LayZhangStrive2 小时前
JUC相关的函数、注解、变量杂记
java·面试·多线程·juc
未秃头的程序猿2 小时前
给公司做了个AI客服Agent,用的Spring AI 1.0,3天上线领导拍板了
java·后端·ai编程
曹牧2 小时前
Eclipse 批量文本替换
java·ide·eclipse
程序员清风3 小时前
OpenAI官方发布最新提示词技巧!
java·后端·面试
梅头脑3 小时前
写了3年CRUD,volatile和synchronized的区别还是答不清——直到我画出了这张三性两锁边界图
java
暮暮祈安3 小时前
Celery 新手入门指南
java·数据库·python·flask·httpx