When using mybatis as a persistence layer, insert, update, delete, sql statements do not return the primary key of the record being operated on by default, but rather the number of records being operated on. When we want to get the primary key automatically generated for the inserted data, we need some additional operations:
- XML file
<!-- useGeneratedKeys="true" Assign the newly added primary key to defined keyProperty (id) -->
<insert id="saveUser" parameterType="com.dao.User" useGeneratedKeys="true" keyProperty="id">
insert into tbl_user ...
</insert>
- Annotation
@Insert("INSERT INTO user ('name') VALUES (#{user.name})")
@Options(useGeneratedKeys=true, keyProperty="id")
public void saveUser(User user);
Now, we can get the generated primary key like this:
userDao.saveUser(user);
String id = user.getId();
0 Comments