【MyBatis-Plus】实现字段自增的5种实现方式 setSql @TableField @Version
创始人
2024-05-31 06:53:00
0

在使用mybatis-plus的时候,我们需要对某条数据的单一字段进行操作,又不想查出整条数据拿到字段值再加一赋值,此时可以用下面5种方式来实现。

方式一:setSql

官网文档Mybatis-Plus:setSql
官方文档示例:
在这里插入图片描述

i.标准setSql

使用setSql实现字段自增

Wrappers.update(Article).setSql("`read_count` = `read_count` + 1");

缺陷: 如果自增字段名变更时, 需要同步修改setSql的字段字符串.

ii.增强setSql(推荐)

为了解决setSql硬编码问题,联想到参照MyBatis-Plus的设计从lambda方法引用中获取字段对应的数据库字段名, 参照主要源码如下:

  • com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper#columnToString(com.baomidou.mybatisplus.core.toolkit.support.SFunction)
  • com.baomidou.mybatisplus.core.toolkit.LambdaUtils#resolve
  • com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper#getColumn
String column = BlueUtil.columnToUnderline(Article::getReadCount);
Wrappers.lambdaUpdate(Article).setSql(CharSequenceUtil.isNotBlank(column), String.format("`%s` = `%s` + 1", column, column));
  1. 根据lambda方法引用获取属性名
public static  String columnToString(SFunction func) {// 根据lambda方法引用获取SerializedLambdaSerializedLambda lambda = com.baomidou.mybatisplus.core.toolkit.LambdaUtils.resolve(func);// 根据SerializedLambda获取方法名,然后截取出属性名return PropertyNamer.methodToProperty(lambda.getImplMethodName());
}
  1. 根据lambda方法引用获取字段名
public static  String columnToUnderline(SFunction func) {String fieldName = InternalUtil.tryCatch(func, BlueUtil::columnToString);return Optional.ofNullable(fieldName).map(CharSequenceUtil::toUnderlineCase).orElse(CharSequenceUtil.EMPTY);
}
  1. BlueUtil.tryCatch
public static  R tryCatch(T t, Function function) {TimeInterval timer = DateUtil.timer();R r = null;try {r = function.apply(t);} catch (Exception e) {log.error(format("内部方法Function调用异常,错误信息:{}", e.getMessage()), e);}log.info("内部方法Function调用,耗时:{}ms", timer.interval());return r;
}

方式二:MyBatis-Plus update 时 column=column+1(@TableField)

官网问答如何 update 时 column=column+1

i.update 时 column=column+1

使用@TableField实现字段自增

@TableField(update = "%s+1", updateStrategy = FieldStrategy.IGNORED)
private Integer readCount;
baseMapper.update(new Article().setUpdateTime(LocalDateTime.now()),Wrappers.
lambdaUpdate().eq(Article::getId, 123) )

注意: 该方式绑定在entity上,baseMapper提供的 update(entity,updateWrapper) 中的entity不能null,而且所有的update方法均不能再改变此值为字段实际的指定值
缺陷: 该baseMapper所有使用这种方式进行更新表操作时, 都会使readCount字段加一; 如果有些更新操作不希望更新readCount时, 要考虑使用其他方式.

ii.乐观锁

使用@TableField实现字段自增(参考上面),在update时给该字段加where限制条件

baseMapper.update(new Article().setUpdateTime(LocalDateTime.now()),Wrappers.
lambdaUpdate().eq(Article::getReadCount, 0).eq(Article::getId, 123) )

方式三:乐观锁(推荐)

官方文档Mybatis-Plus 乐观锁
Mybatis-Plus基于@Version注解的乐观锁实现

使用@Version实现字段自增

  1. 实例化OptimisticLockerInnerInterceptor,并添加到MyBatis-Plus的拦截器链中;
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return mybatisPlusInterceptor;
}
  1. readCount字段加上@Version注解。
@Version
private Integer readCount;

注意:

  • 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下newVersion = oldVersion + 1
  • newVersion会回写到entity
  • 仅支持updateById(id)update(entity, wrapper)方法
  • entity的版本字段必须有值,否则不会生成乐观锁SQL
  • update(entity, wrapper)方法下,wrapper不能复用!!!

MyBatis-Plus开启SQL日志

官网文档启动 mybatis 本身的 log 日志

mybatis-plus.configuration.log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

参考文档

Mybatis-Puls条件构造器setSql
Mybatis-Puls如何实现字段自增1
Mybatis-Puls如何 update 时 column=column+1
Mybatis-Plus 乐观锁
Mybatis-Plus 乐观锁
Mybatis-Plus基于@Version注解的乐观锁实现
启动 mybatis 本身的 log 日志

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...