向数据库插入一条数据同时获取主键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>
相关推荐
千寻技术帮6 小时前
基于微信小程序的零食销售系统(源码+文档+脚本)50047
数据库·mysql·微信小程序·小程序·毕业设计·springboot·课程设计
张人玉7 小时前
C#如何使用FreeSql连接数据库
数据库·c#·freesql
会编程的吕洞宾7 小时前
Spring Cloud Gateway 限流鉴权与灰度发布实战
java·经验分享·后端·spring
codeejun7 小时前
每日一Go·MySQL-25、如何解决高并发写冲突?
数据库·mysql
YYYing.7 小时前
【Redis剑指offer系列 (三) 】Redis事务与日志
数据库·redis·缓存·日志·八股
Rain的Java大神之路9 小时前
别再背概念了:中台不是大数仓,湖仓一体也不是“湖+仓”——从电商下单链路一次讲透数据库、数仓、数据湖、中台、湖仓一体
大数据·数据库·后端
AI开源软件9 小时前
SpringCloud+Nacos 业务协同落地:业务调用与集成中心远程管理如何分别配置
java·spring boot
inferno9 小时前
十六、日志管理
数据库·sql·mysql
sharemylove18 小时前
Java集合框架全面详解
java·开发语言·经验分享·笔记·学习
FYKJ_201018 小时前
springboot众创项目团队管理系统94666-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·spark·课程设计