How to implement optimistic locking in MyBatis?

Implementing optimistic locking in MyBatis can be achieved by adding a version number field in the corresponding entity class and updating this field in the corresponding update operation. The specific steps are as follows:

  1. Add a version number field in the entity class, for example:
public class User {
    private Long id;
    private String name;
    private Integer version;
    
    // getters and setters
}
  1. Add an update operation method in the corresponding Mapper interface, and update the version number field in the SQL statement.
<update id="updateUser" parameterType="User">
    UPDATE user
    SET name = #{name}, version = version + 1
    WHERE id = #{id} AND version = #{version}
</update>
  1. For updating operations in the corresponding Service, the original version number must be passed in, for example:
public void updateUser(User user) {
    int rows = userMapper.updateUser(user);
    if (rows == 0) {
        throw new OptimisticLockException("更新失败,数据已被修改");
    }
}

This allows optimistic locking to be implemented in MyBatis. During update operations, if the version number does not match, the update operation will fail and throw an exception.

bannerAds