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

时间:2011-10-10 09:22:48

标签: java oracle annotations mybatis

我在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);

它应该返回新的genarated ID,但它返回“1”,即使它以适当的方式插入表中。

任何人都可以试试这个“使用oracle获取ID或者在MyBatis(注释)中插入ID”

2 个答案:

答案 0 :(得分:3)

阅读MyBatis Documentation

  

keyProperty是MyBatis将密钥设置为的字段   getGeneratedKeys,或者插入的selectKey子元素   言。

所以,给定一个带有字段的Pojo" id"使用get和set方法。在运行Mapper类的insert语句之后,将使用生成的键值设置pojo上的id字段。

答案 1 :(得分:3)

感谢所有人的回复,但我在这里得到的解决方案是......

@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")

现在它将返回新创建的ID