I am trying to learn MyBatis. How to do I get the auto-generated ID after I have inserted a statement using the @InsertAnnotation.
Example of my code:
@Insert("INSERT INTO user(name, mobile, password) VALUES(#{name}, #{mobile}, #{password})")
@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false, resultType = Long.class)
Long insertUser(User user);
I want to get the generated id as the return from the insert method.
@SelectKey is for legacy drivers.
For recent drivers, you should use useGeneratedKeys.
We have an FAQ entry explaining how to do it with XML mapper.
With annotation, it would look as follows.
@Insert("INSERT INTO user(name, mobile, password) VALUES(#{name}, #{mobile}, #{password})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);
Note that @Insert method returns the number of updated rows, not the generated key.
The generated key is assigned to the property of the parameter specified by keyProperty i.e. User.id in your case.
For some databases, you might need to specify keyColumn as well.
If it didn't work, please add versions of DB, driver and MyBatis to the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With