向数据库插入一条数据同时获取主键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>
相关推荐
默默敲代码的徐哥儿4 分钟前
八股文整理——后端
java·开发语言·spring boot·后端·学习
EterNity_TiMe_5 分钟前
别让告警变成噪音:用Prometheus和Alertmanager搭一套可远程查看的监控系统
数据库·人工智能·ai·postgresql·prometheus·cpolar
不超限29 分钟前
Postgresql 数据库 自增字段,Vastbase 无效的问题
数据库
折哥的程序人生 · 物流技术专研37 分钟前
第2篇:策略模式三大角色拆解与UML
java·设计模式·策略模式·uml·编程入门·行为型模式·扩充系列
李少兄41 分钟前
Java CompletableFuture 解析(含常见面试题)
java·开发语言
名字还没想好☜41 分钟前
Spring Boot 全局异常处理:@ControllerAdvice 实战
java·spring boot·后端·spring·异常处理
能摆一天是一天44 分钟前
Spring ai vectorstore 使用本地模型导致只能匹配可行度为1.0的内容的解决方法笔记
java·笔记·spring
阿坤带你走近大数据1 小时前
Oracle新老SQL写法对比
数据库·sql·oracle
我命由我123451 小时前
方差(实例实操、与标准差的区别)
java·数据结构·算法·数据分析·java-ee·intellij-idea·idea
Java内核笔记1 小时前
Spring Security 源码解析(八)方法安全授权与自定义扩展:@EnableMethodSecurity、AOP、SpEL 全链路
java·后端