如何在带有注释的 mybatis 和 oracle 中插入时返回 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7710759/
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-09-19 00:21:40  来源:igfitidea点击:

How to return IDs on insert in mybatis and oracle with annotation

javaoracleannotationsmybatis

提问by Rajeev

I am trying the following in Java

我正在 Java 中尝试以下操作

@Insert("INSERT INTO USERS (ID,NAME,AGE) VALUES(USER_SEQ.NEXTVAL,#{name},#{age})")
@Options(useGeneratedKeys=true, keyProperty="ID", keyColumn="ID")
public int insertUsers(User userBean);

It should return the new genarated ID, but its returning "1" always even though its making insertion into table in a proper way.

它应该返回新生成的 ID,但它总是返回“1”,即使它以正确的方式插入到表中。

Can any one have tryied this "Getting IDs in return or insertion in MyBatis(annotation) with oracle"

任何人都可以尝试“使用oracle在MyBatis(注释)中返回或插入ID”

回答by Andy

Read the MyBatis Documentation.

阅读MyBatis 文档

The keyProperty is the field that MyBatis will set the key into by getGeneratedKeys, or by a selectKey child element of the insert statement.

keyProperty 是 MyBatis 将通过 getGeneratedKeys 或插入语句的 selectKey 子元素设置键的字段。

So, given a Pojo with a field "id" with get and set methods. After the insert statement with the Mapper class is ran, the id field on the pojo will be set with the generated key value.

因此,给定一个带有 get 和 set 方法的字段“id”的 Pojo。运行 Mapper 类的插入语句后,pojo 上的 id 字段将设置为生成的键值。

回答by Rajeev

Thanks all for your responses, but i have got the solution here it is.....

感谢大家的回复,但我在这里得到了解决方案......

@Insert("INSERT INTO USERS (NAME,AGE) VALUES(#{name},#{age})") 
@SelectKey(statement="select STANDARDS_ID_SEQ.CURRVAL from dual", resultType = int.class, before = false, keyProperty = ID)
@Options(useGeneratedKeys=true, keyProperty="ID", keyColumn="ID")

now it will return the new created ID

现在它将返回新创建的 ID