问题:
使用mybatis plus提供的封装方法updatebyid()时,字段从前台传入的数据为空值,但是执行方法后该字段未得到更新。
以前使用原生mybatis生成的update方法,是有对值是否为空的判断,如果为空就不加入到update table set语句内,那么mybatis plus是不是会有类似于@tablefield、@tableid这样的注解,能解决该问题呢
解决:
方案一 注解方式
进入@tablefield注解的相关内容。
在该注解的属性描述内,有这样一个字段——“fill”,字段自动填充策略。
| fill | enum | 否 | fieldfill.default | 字段自动填充策略 |
它决定了在执行新增或修改方法时,有这个注解的字段需要怎样将数据进行填充,fieldfill的相关的属性,官方描述如下:
| 值 | 描述 |
|---|---|
| default | 默认不处理 |
| insert | 插入时填充字段 |
| update | 更新时填充字段 |
| insert_update | 插入和更新时填充字段 |
默认值是default,默认不处理,即本次出现的问题——新增、修改该字段为空时,将不自动填充即不列入语句,如:
insert into shop_item(shop_price) values(xxxx); update shop_item set shop_price = xxxx;
@data
@tablename("shop_item")
public class shopitem implements serializable {
private static final long serialversionuid = 1l;
/**
* 编号
*/
@tableid(type= idtype.input)
private string id;
/**
* 物品名称
*/
private string itemname;
/**
* 物品价格
*/
@tablefield(fill = fieldfill.update)
private double itemprice;
/**
* 添加人编号
*/
private string adduserid;
/**
* 添加时间
*/
private date addtime;
}
在itemprice属性的顶上加上@tablefield(fill = fieldfill.update)后,在执行一遍查看sql
update
shop_item
set
item_name = 'iphone',
item_price = ''
where
id = '361e8c48-6699-4ed5-83c4-7c9d98747c2c';
方案二 全局配置
根据方案一中,fieldstrategy 的三种策略:ignored、not_null、not_empty,
可以在 application.yml 配置文件中注入配置 globalconfiguration 属性 update-strategy,
将 update-strategy 策略调整为 ignored,即忽略判断策略。即可调整全局的验证策略。
如下所示:
# yml 配置:
mybatis-plus:
global-config:
db-config:
update-strategy: ignored全局性配置会对所有的字段都忽略判断,如果有特殊字段处理,可以单独配置,修改字段的策略。
设定全局配置,可以减少一个一个字段去指定增加的麻烦。
方案三:使用 updatewrapper (3.x) 更新
mp 提供了 updatewrapper 类简化更新的操作,
针对方法级进行操作,只需操作其更新方法,相比较方案一和方案二,方案三影响范围较小。
由于 basemapper 的继承 mapper ,在 basemapper
/** * 根据 whereentity 条件,更新记录 * * @param entity 实体对象 (set 条件值,可以为 null) * @param updatewrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句) */ int update(@param(constants.entity) t entity, @param(constants.wrapper) wrapper<t> updatewrapper);
看出,实体对象可以 set 条件值且为可以为 null,说明有两种方法可以实现更新操作(采用 lambda 表达式):
- 将需要更新的字段,设置到 entity 中
- 将 entity设置为 null ,将需要更新的字段设置到 updatewrapper 中
mapper.update(
null,
wrappers.<user>lambdaupdate()
.set(user::getage, 3)
.set(user::getname, "mp")
.set(user::getemail, null) //把email设置成null
.eq(user::getid, 2)
);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论