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
Related videos on Youtube
Author by
Rajeev
Updated on June 04, 2022Comments
-
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 about 12 yearsSounds 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 over 10 yearsTo show an explicit example: Say you have a
Student
pojo with anid
attribute. Create your new student and callstudentMapper.addNewStudent(student);
Nowstudent.getId()
contains the auto number, not the return value fromaddNewStudent()
- that will always be the number of rows affected.