实际上,可以通过 @Options 注释来做到这一点(前提是您在数据库中使用 auto_increment 或类似的东西):
@Insert("insert into table3 (id, name) values(null, #{name})")
@Options(useGeneratedKeys=true, keyProperty="idName")
int insertTable3(SomeBean myBean);
请注意,如果 SomeBean 中的 key 属性名为“id”,则不需要 keyProperty="idName" 部分。还有一个keyColumn 属性可用,用于MyBatis 自己找不到主键列的极少数情况。另请注意,通过使用@Options,您将您的方法提交给一些默认参数;查阅文档很重要(链接如下——当前版本的第 60 页)!
(旧答案)(相当新的)@SelectKey 注释可用于更复杂的密钥检索(序列、identity() 函数...)。以下是MyBatis 3 User Guide (pdf) 提供的示例:
这个例子展示了使用@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);
这个例子展示了使用@SelectKey 注解在插入之后检索一个标识值:
@Insert("insert into table2 (name) values(#{name})")
@SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
int insertTable2(Name name);