JasonLaw
V2EX  ›  编程

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

  •  
  •   JasonLaw · Mar 10, 2021 · 2417 views
    This topic created in 1891 days ago, the information mentioned may be changed or developed.

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

    4 replies    2021-03-10 17:12:33 +08:00
    ewq
        1
    ewq  
       Mar 10, 2021
    官方文档
    ```
    这个例子展示了如何使用 @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  
       Mar 10, 2021
    useGeneratedKeys="true", keyProperty="id"
    arthas2234
        3
    arthas2234  
       Mar 10, 2021
    上 MyBatis-Plus
    liuxiaohua
        4
    liuxiaohua  
       Mar 10, 2021
    百度一下就知道了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5531 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 08:21 · PVG 16:21 · LAX 01:21 · JFK 04:21
    ♥ Do have faith in what you're doing.