MyBatis useGeneratedKeys: Complete Guide

In MyBatis, useGeneratedKeys parameter can be used by configuring elements.

For example, defining a method in the Mapper interface as shown below:

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

In this example, the useGeneratedKeys parameter is set to true in the @Options annotation, indicating that database-generated primary key values should be used. keyProperty specifies which property of the User object the generated primary key value should be set to.

When the insert method is called to insert a record, MyBatis will call the database to generate the primary key value and set that value to the id property of the User object.

bannerAds