我没有找到与<selectkey>
匹配的注释(请参阅此open issue)
我该怎么办?
检查mybatis代码显示INSERT
是通过UPDATE
实现的,并且始终返回插入的行数!所以...除非我在这里完全遗漏了一些东西,否则使用当前的(3.0.3)实现无法做到这一点。
答案 0 :(得分:26)
实际上,可以使用@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);
答案 1 :(得分:13)
<insert>
,<update>
和<delete>
语句返回受影响的行数,这与数据库API一样。
如果为插入的行生成了新ID,它将反映在作为参数传递的对象中。因此,例如,如果在带注释的插入方法中调用mapper.insert(someObject),则在插入之后,可以调用someObject.getId(或类似)来检索它。
使用<insert>
的选项,您可以调整(通过提供SQL语句)和何时(实际插入之前或之后)生成或检索id,以及放置对象的位置。
使用MyBatis generator从数据库模式生成类并查看如何处理插入和更新可能是有益的。具体来说,生成器生成“示例”类,用作临时容器来传递数据。
答案 2 :(得分:1)
你可以从保存方法中获取生成的id, 让我们说一个具有ID和名称属性的bean,
bean.setName("xxx");
mapper.save(bean);
// here is your id
logger.debug(bean.getID);