MyBatis useGeneratedKeys Explained

In MyBatis, the useGeneratedKeys parameter is used to specify whether to return the generated primary key value after an insert operation. When set to true, MyBatis will set the generated primary key value back into the inserted object, so that the new primary key value of the inserted record can be directly obtained after the insert operation.

Typically, databases will automatically generate a unique value for the primary key field, such as an auto-incrementing integer or UUID. By setting the useGeneratedKeys parameter to true, MyBatis can automatically assign the generated primary key value to the corresponding object property, making it easier for future operations.

The example code is shown below:

@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);

In this example, useGeneratedKeys is set to true and the generated primary key value is assigned to the id property of the User object through keyProperty = “id”. This allows for retrieving the primary key value of the newly inserted record directly using the user.getId() method after the insertion operation.

bannerAds