Java 如何在带有注释的mysql中使用mybatis返回插入的id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4283159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:21:39  来源:igfitidea点击:

How to return ids on Inserts with mybatis in mysql with annotations

javamysqlmybatis

提问by ripper234

  • See this related questionfor Postgres. For some reason, the solution doesn't work for me - the return value of the insert statement is always "1".
  • See this other question for an XML based solution. I would like to do the same without XML - insert a record and find the new auto-generated id of the record I just insreted.
  • 请参阅Postgres 的此相关问题。出于某种原因,该解决方案对我不起作用 - 插入语句的返回值始终为“1”。
  • 有关基于 XML 的解决方案,请参阅此其他问题。我想在没有 XML 的情况下做同样的事情 - 插入一条记录并找到我刚刚插入的记录的新自动生成的 id。

I didn't find a matching annotation to <selectkey>(see this open issue) How do I proceed?

我没有找到匹配的注释<selectkey>(请参阅此未解决的问题)我该如何继续?

Examining mybatis code reveals that INSERTis implemented via UPDATE, and always returns the number of inserted rows! So ... unless I'm completely missing something here, there's no way to do this using the current (3.0.3) implementation.

检查 mybatis 代码发现它INSERT是通过 实现的UPDATE,并且总是返回插入的行数!所以......除非我在这里完全遗漏了一些东西,否则无法使用当前的(3.0.3)实现来做到这一点。

回答by Daniel Novak

The <insert>, <update>and <delete>statements return the number of affected rows, as is common with database APIs.

<insert><update><delete>语句返回受影响的行数,如与数据库API常见。

If a new ID is generated for the inserted row, it is reflected in the object you passed as a parameter. So for example, if you call mapper.insert(someObject) inside your annotated insert method, after inserting, you can call someObject.getId (or similar) to retrieve it.

如果为插入的行生成新 ID,它会反映在您作为参数传递的对象中。因此,例如,如果您在带注释的插入方法中调用 mapper.insert(someObject),则在插入后,您可以调用 someObject.getId(或类似方法)来检索它。

Using the options of <insert>, you can tweak how (by providing an SQL statement) and when (before or after the actual insertion) the id is generated or retrieved, and where in the object it is put.

使用 的选项<insert>,您可以调整如何(通过提供 SQL 语句)和何时(在实际插入之前或之后)生成或检索 id,以及它在对象中的位置。

It may be instructive to use the MyBatis generatorto generate classes from a database schema and have a look at how inserts and updates are handled. Specifically, the generator produces "example" classes that are used as temporary containers to pass around data.

使用MyBatis 生成器从数据库模式生成类并查看插入和更新是如何处理的可能会有所启发。具体来说,生成器生成用作临时容器来传递数据的“示例”类。

回答by edwinkun

you can get your generated ids from save methods, lets say a bean with ID and name properties,

您可以从保存方法中获取生成的 ID,比如说一个带有 ID 和名称属性的 bean,

bean.setName("xxx");
mapper.save(bean);
// here is your id
logger.debug(bean.getID);

回答by Manur

Actually, it's possible to do it, with the @Optionsannotation (provided you're using auto_increment or something similar in your database) :

实际上,可以使用@Options注释来做到这一点(前提是您在数据库中使用了 auto_increment 或类似的东西):

@Insert("insert into table3 (id, name) values(null, #{name})") 
@Options(useGeneratedKeys=true, keyProperty="idName")
int insertTable3(SomeBean myBean); 

Note that the keyProperty="idName"part is not necessary if the key property in SomeBean is named "id". There's also a keyColumnattribute available, for the rare cases when MyBatis can't find the primary key column by himself. Please also note that by using @Options, you're submitting your method to some default parameters ; it's important to consult the doc (linked below -- page 60 in the current version) !

请注意,keyProperty="idName"如果 SomeBean 中的 key 属性名为“id” ,则该部分不是必需的。还有一个keyColumn属性可用,用于MyBatis 自己找不到主键列的罕见情况。另请注意,通过使用@Options,您将您的方法提交给一些默认参数;请务必查阅文档(链接如下 - 当前版本中的第 60 页)!

(Old answer)The (quite recent) @SelectKeyannotation can be used for more complex key retrieval (sequences, identity() function...). Here's what the MyBatis 3 User Guide(pdf) offers as examples :

(旧答案)(最近的)@SelectKey注释可用于更复杂的密钥检索(序列、identity() 函数...)。以下是MyBatis 3 用户指南(pdf) 提供的示例:

This example shows using the @SelectKey annotation to retrieve a value from a sequence before an insert:

此示例显示使用 @SelectKey 注释在插入之前从序列中检索值:

@Insert("insert into table3 (id, name) values(#{nameId}, #{name})") 
@SelectKey(statement="call next value for TestSequence", keyProperty="nameId", before=true, resultType=int.class) 
int insertTable3(Name name); 

This example shows using the @SelectKey annotation to retrieve an identity value after an insert:

此示例显示使用 @SelectKey 注释在插入后检索标识值:

@Insert("insert into table2 (name) values(#{name})")
@SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
int insertTable2(Name name);