其实,这是有可能做到这一点,与@Options
注解(前提是你使用AUTO_INCREMENT或数据库中的类似的东西):
@Insert("insert into table3 (id, name) values(null, #{name})")
@Options(useGeneratedKeys=true, keyProperty="idName")
int insertTable3(SomeBean myBean);
注意,如果在SomeBean关键属性名为“ID”的部分是没有必要的。还有一个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);
假设您使用注释选择并使用@Options(useGeneratedKeys = true) – Lucky 2016-03-03 09:16:53