V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
JasonLaw
V2EX  ›  编程

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

  •  
  •   JasonLaw · 2021-03-10 15:40:17 +08:00 · 1586 次点击
    这是一个创建于 1136 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    4 条回复    2021-03-10 17:12:33 +08:00
    qgs
        1
    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
        2
    zsedc  
       2021-03-10 15:54:30 +08:00
    useGeneratedKeys="true", keyProperty="id"
    arthas2234
        3
    arthas2234  
       2021-03-10 15:58:38 +08:00
    上 MyBatis-Plus
    liuxiaohua
        4
    liuxiaohua  
       2021-03-10 17:12:33 +08:00
    百度一下就知道了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3860 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 10:16 · PVG 18:16 · LAX 03:16 · JFK 06:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.