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 策略内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论