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

10,942

Solution 1

Read the MyBatis Documentation.

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

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.

Solution 2

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

Share:
10,942

Related videos on Youtube

Rajeev
Author by

Rajeev

Updated on June 04, 2022

Comments

  • Rajeev
    Rajeev over 1 year

    I am trying the following in 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.

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

    • Rajeev
      Rajeev about 12 years
      Sounds good but dear i can't do it because i am working on a existing system & frameork and i can make such kind of changes.
  • Owen O Byrne
    Owen O Byrne over 10 years
    To show an explicit example: Say you have a Student pojo with an id attribute. Create your new student and call studentMapper.addNewStudent(student); Now student.getId() contains the auto number, not the return value from addNewStudent() - that will always be the number of rows affected.