sharp-database通过注解@Version实现乐观锁

当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:

取出记录时,获取当前 version
更新时,带上这个 version
执行更新时, set version = newVersion where version = oldVersion
如果 version 不对,就更新失败(更新影响的行数为0)

Notice.java 属性添加 @Version

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@SuperBuilder
@Table(value = "t_notice", comment = "通知公告")
public class Notice extends BaseEntity {

    String name;

    @Version
    Integer version;

}

生成SQL语句

create table `sharp-demo`.t_notice
(
    id          bigint      not null comment '主键'
        primary key,
    name        varchar(32) null,
    version     int         not null comment '版本号',
    create_by   bigint      null,
    create_time datetime    null comment '创建时间',
    update_by   bigint      null,
    update_time datetime    null comment '修改时间',
    is_deleted  bit         null comment '是否逻辑删除'
)
    comment '通知公告' charset = utf8mb3;

测试

新增

    @Order(0)
    @Test
    public void testNoticeInsert() {
        noticeDAO.insert(Notice.builder()
                        .name("hello new version")
                .build());
        // SQL => [INSERT INTO t_notice(name,version,create_by,create_time,update_by,update_time,is_deleted,id) VALUES(?,?,?,?,?,?,?,?)], args:=> [[hello new version, 1, 0, 2023-05-14T03:08:00.944, 0, 2023-05-14T03:08:00.944, false, 688973584810381312]]
    }

修改

    @Order(1)
    @Test
    public void testNoticeUpdate() {
        Notice notice = noticeDAO.selectById(688436409735868416L).get();
        notice.setName("new didi");
        noticeDAO.update(notice);
        // SQL => [UPDATE t_notice SET name = ?,version = ?,update_by = ?,update_time = ?,is_deleted = ? WHERE id = ? AND version = ? AND is_deleted = ?], args:=> [[new didi, 2, 0, 2023-05-12T15:33:28, false, 688436409735868416, 1, false]]
    }