@TableField 是 MyBatis-Plus 框架提供的注解,用于自定义实体类字段与数据库表字段的映射关系。
@TableField(
value = "column_name", // 数据库字段名
exist = true, // 是否为数据库字段(默认true)
fill = FieldFill.DEFAULT, // 自动填充策略
select = true, // 是否参与查询(默认true)
update = "%s+1", // 自定义更新条件,this is 更新时自增
condition = SqlCondition.EQUAL, // where条件比较方式
jdbcType = JdbcType.UNDEFINED, // JDBC类型
typeHandler = UnknownTypeHandler.class, // 类型处理器
insertStrategy = FieldStrategy.DEFAULT, // 插入策略
updateStrategy = FieldStrategy.DEFAULT, // 更新策略
whereStrategy = FieldStrategy.DEFAULT, // where条件策略
keepGlobalFormat = false, // 是否保持全局format
numericScale = "" // 小数位数(保留精度)
)
private String username;
常见应用场景:
场景 1:字段名映射(最常用)
@Data
public class User {
private Long id;
// 数据库字段名为 user_name,实体类为 username
@TableField(value = "user_name")
private String username;
// 数据库字段名为 create_time,驼峰命名自动映射也可,但显式指定更清晰
@TableField("create_time")
private LocalDateTime createTime;
}
场景 2:排除非表字段
@Data
public class User {
private Long id;
private String name;
// 该字段仅用于业务计算,数据库表中没有
@TableField(exist = false)
private BigDecimal tempBonus;
// 前端查询条件,不存入数据库
@TableField(exist = false)
private String keyword;
}
场景 3:自动填充(审计字段)
@Data
public class BaseEntity {
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(value = "create_by", fill = FieldFill.INSERT)
private Long createBy;
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
private Long updateBy;
}
场景 4:查询时排除敏感字段
@Data
public class User {
private Long id;
private String username;
// 密码字段:查询时不返回,但插入/更新时参与
@TableField(select = false)
private String password;
// 手机号:查询时脱敏处理(配合 typeHandler)
@TableField(typeHandler = MaskPhoneTypeHandler.class)
private String phone;
}
"查询时脱敏"是一种数据安全保护机制,指在从数据库查询数据时,自动将敏感信息(如手机号、身份证号、银行卡号等)转换为掩码形式,防止完整信息泄露。
例子:


场景 5:自定义更新逻辑
@Data
public class Product {
private Long id;
// 乐观锁:更新时 version = version + 1
@TableField(update = "%s+1")
private Integer version;
// 库存扣减:更新时 stock = stock - #{stock}
@TableField(update = "stock - #{stock}")
private Integer stock;
}
javaType应用场景:
@Data
public class User {
private String name;
// 明确告诉 MyBatis:这个 Integer 对应数据库的 INTEGER 类型
@TableField(jdbcType = JdbcType.INTEGER)
private Integer age;
@TableField(jdbcType = JdbcType.VARCHAR)
private String email;
}

常用属性速查:

8659



被折叠的 条评论
为什么被折叠?



