向数据库插入一条数据同时获取主键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>
相关推荐
SamDeepThinking36 分钟前
裁掉那个差程序员后,给你看团队里高手的代码:这个习惯,希望你有
java·后端·程序员
朕瞧着你甚好2 小时前
技术雷达 & Java 集成评估报告 — Apache Tika 3.3.1
java·ai编程
vivo互联网技术2 小时前
从 10 分钟到 1 秒:ES 深度分页任意跳页的三轮优化实战
服务器·数据库·redis·elasticsearch·深度分页
MacroZheng2 小时前
短短几天,暴涨2.8万Star!又一款编程神器开源!
java·人工智能·后端
SamDeepThinking3 小时前
函数式编程:用BiFunction消除多类型分支的代码重复
java·后端·面试
倔强的石头_17 小时前
《Kingbase护城河》——猎捕慢查询:执行计划的微观解析与索引调优实战
数据库
SelectDB19 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
Flittly20 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了20 小时前
Java 生成二维码解决方案
java·后端
人活一口气1 天前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot