更新时间:2023-10-06 10:58:04
实际上,可以使用 @Options
注释(假设您在数据库中使用auto_increment或类似内容)来执行此操作:
Actually, it's possible to do it, with the @Options
annotation (provided you're using auto_increment or something similar in your database) :
@Insert("insert into table3 (id, name) values(null, #{name})")
@Options(useGeneratedKeys=true, keyProperty="idName")
int insertTable3(SomeBean myBean);
请注意 keyProperty =idName
如果SomeBean中的key属性被命名为id,则不需要part。还有一个 keyColumn
属性可用,因为MyBatis无法自己找到主键列的极少数情况。另请注意,通过使用 @Options
,您将方法提交到某些默认参数;查阅文档非常重要(链接如下 - 当前版本的第60页)!
Note that the keyProperty="idName"
part is not necessary if the key property in SomeBean is named "id". There's also a keyColumn
attribute 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) !
(旧答案)(最近) @SelectKey
注释可用于更复杂的密钥检索(序列,identity()函数...)。这是 MyBatis 3用户指南(pdf)提供了示例:
(Old answer) The (quite recent) @SelectKey
annotation can be used for more complex key retrieval (sequences, identity() function...). Here's what the MyBatis 3 User Guide (pdf) offers as examples :
此示例显示使用@SelectKey批注检索
插入前的序列中的值:
This example shows using the @SelectKey annotation to retrieve a value from a sequence before an insert:
@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);
此示例显示使用@SelectKey批注后检索标识值插入:
This example shows using the @SelectKey annotation to retrieve an identity value after an insert:
@Insert("insert into table2 (name) values(#{name})")
@SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
int insertTable2(Name name);