当前位置: 代码网 > it编程>编程语言>Java > mybatisPlus FieldStrategy 策略作用小结

mybatisPlus FieldStrategy 策略作用小结

2025年12月10日 Java 我要评论
mybatis-plus 的 fieldstrategy 枚举用于控制实体字段在 插入(insert)、更新(update) 和 查询条件(where) 中的空值处理策略。理解这些策略对避免数据异常非

mybatis-plus 的 fieldstrategy 枚举用于控制实体字段在 插入(insert)更新(update)查询条件(where) 中的空值处理策略。理解这些策略对避免数据异常非常重要,以下是详细解释:

一、各策略的作用

1.ignored

  • 作用忽略空值判断,无论字段值是否为 null、空字符串("") 或空集合,都会参与 sql 操作。
  • 场景:强制将字段更新为 null(解决 saveorupdate 无法更新 null 的问题)。

2.not_null

  • 作用仅忽略 null,非 null 的空字符串或空集合仍会参与 sql 操作。
  • 场景:允许字段为空字符串,但不允许 null(如数据库字段允许 '' 但不允许 null)。

3.not_empty

  • 作用忽略 null、空字符串("") 和空集合
  • 场景:字符串或集合类型字段必须有实际值(如用户名、列表数据)。

4.default

  • 作用全局默认策略,通常等价于 not_null(取决于 mybatis-plus 版本)。
  • 场景:使用全局配置的默认行为。

5.never

  • 作用永远不参与 sql 操作,无论值是什么。
  • 场景:字段仅用于业务逻辑,不与数据库交互(如临时计算字段)。

二、不同方法(insert/update/where)的策略差异

1.insertstrategy(插入时)

  • 影响范围save()savebatch() 等插入方法。
  • 示例
    @tablefield(insertstrategy = fieldstrategy.not_null)
    private string username; // 插入时忽略 null 值
    

2.updatestrategy(更新时)

  • 影响范围updatebyid()saveorupdate()update(entity, wrapper) 等更新方法。
  • 示例
    @tablefield(updatestrategy = fieldstrategy.ignored)
    private string email; // 更新时允许将 email 设置为 null
    

3.wherestrategy(查询条件时)

  • 影响范围wrapper 条件构造器中的实体参数。
  • 示例
    @tablefield(wherestrategy = fieldstrategy.not_empty)
    private string phone; // 查询条件中忽略空字符串和 null
    

三、策略对比表

策略插入(insert)更新(update)查询条件(where)
ignored字段值无论如何都插入字段值无论如何都更新字段值无论如何都作为条件
not_null忽略 null,插入其他值忽略 null,更新其他值忽略 null,其他值作为条件
not_empty忽略 null、""、空集合忽略 null、""、空集合忽略 null、""、空集合
default按全局配置(通常为 not_null)按全局配置(通常为 not_null)按全局配置(通常为 not_null)
never字段不参与插入字段不参与更新字段不作为条件

四、常见应用场景

1. 允许更新字段为null

@tablefield(updatestrategy = fieldstrategy.ignored)
private string remark; // 允许将备注更新为 null

2. 插入时自动填充默认值

@tablefield(insertstrategy = fieldstrategy.not_null)
private integer status = 1; // 插入时若未设置值,则使用默认值 1

3. 避免空字符串作为查询条件

@tablefield(wherestrategy = fieldstrategy.not_empty)
private string keyword; // 避免空字符串作为查询条件

五、全局配置 vs 字段注解

  • 全局配置(优先级低):

    mybatis-plus:
      global-config:
        db-config:
          insert-strategy: not_null
          update-strategy: not_null
          where-strategy: not_empty
    
  • 字段注解(优先级高):

    @tablefield(insertstrategy = fieldstrategy.ignored, 
                updatestrategy = fieldstrategy.not_null)
    private string nickname;
    

六、总结

  • ignored:强制让 null 参与 sql 操作,解决 saveorupdate 无法更新 null 的问题。
  • not_null:最常用,避免 null 导致数据库字段被意外覆盖。
  • not_empty:适合字符串和集合类型,确保有实际数据。
  • 更新 null 字段:优先使用 fieldstrategy.ignored 注解,而非全局配置。

合理配置这些策略可以避免 null 值导致的意外数据问题,提高代码健壮性。

到此这篇关于mybatisplus fieldstrategy 策略作用的文章就介绍到这了,更多相关mybatisplus fieldstrategy 策略内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com