使用 MyBatis,怎么优雅地获取到 insert 时自动生成的 id?

2021-03-10 15:40:17 +08:00
 JasonLaw

我找了一些资料,比如说java - MyBatis, how to get the auto generated key of an insert? [MySql] - Stack Overflow中的一个回答,但是太丑陋了,有优雅一点的方法吗?

1614 次点击
所在节点    编程
4 条回复
qgs
2021-03-10 15:52:34 +08:00
官方文档
```
这个例子展示了如何使用 @SelectKey 注解来在插入后读取数据库自增列的值:

@Insert("insert into table2 (name) values(#{name})")
@SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
int insertTable2(Name name);
```
zsedc
2021-03-10 15:54:30 +08:00
useGeneratedKeys="true", keyProperty="id"
arthas2234
2021-03-10 15:58:38 +08:00
上 MyBatis-Plus
liuxiaohua
2021-03-10 17:12:33 +08:00
百度一下就知道了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/760359

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX