SpringBoot + Mybatis Plus:对象entity属性值为null时,更新的问题

工程框架为SpringBoot+Mybatis-Plus,使用Mybatis-Plus核心的功能:代码生成器,可以生成Controller,Service,Mapper,Entity实体等代码,并且在Service层,可以通过this.save等进行实体对象的保存,更新,删除等操作,同时还支持QueryWrapper、UpdateWrapper条件选择器。

问题:实体类对应的数据库表中,一开始维护了一条记录,所有字段都有值;在Service层创建一个新的实体对象,部分属性值为null 调用this.updateById时,数据库中对应的那条全记录数据,只要是新实体对象中为null的属性对应的数据库表字段都改为了NULL。

解决:

方法一:

在application.yml文件中,进行Mybatis-Plus全局更新策略配置

## mybatis plus
mybatis-plus:
  # Mybatis Mapper所对应的XML文件位置
  mapper-locations: mapper/**/**Mapper.xml
  type-aliases-package: com.inspur.tax.**.entity
  check-config-location: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    call-setters-on-nulls: true
    jdbc-type-for-null: 'null'
    auto-mapping-unknown-column-behavior: warning
  global-config:
    banner: false
    db-config:
      # 主键类型 0:数据库ID自增 1:未定义 2:用户输入 3:id_worker 4:uuid 5:id_worker字符 
      # 串表示
      id-type: UUID
      # 字段策略 0:“忽略判断”,1:“非NULL判断” 2:“非空判断”
      field-strategy: 1
      capital-mode: true
      column-underline: true
      refresh-mapper: true

 根据自己的需要,修改Mybatis-Plus 全局配置里的字段策略。如果将field-strategy设置为1,则实体对象中属性为NULL既未赋值的属性,不会将数据库中对应的字段修改为NULL。

方法二:

在实体属性上面单独进行配置@TableField(strategy = FieldStrategy.IGNORED),需要注意的是它会覆盖全局策略。

 
  

同时注解TanleField的strategy属性还有3个值

NOT_NULL, 非NULL判断

NOT_EMPTY, 非空判断

DEFAULT, 默认

IGNORED,忽略判断

具体会有什么效果,没有测试,我使用的是方法一。

你可能感兴趣的:(Mybatis,SpringBoot)