在MyBatis-Plus中,@TableField
注解用于控制实体类与数据库表字段之间的映射关系。通过合理使用 @TableField
注解,可以更灵活地控制字段的映射、查询和插入等行为。以下是对@TableField注解的深入理解和使用方法的详细介绍。
基本用法
@TableField
注解主要用于字段的属性映射,通常使用在实体类的字段上。其常见的属性包括 value
、exist
、fill
等。
1. value
属性
value
属性用于指定数据库表中的实际字段名称。如果实体类的字段名与数据库表字段名不一致,可以通过 value
属性进行映射。
import com.baomidou.mybatisplus.annotation.TableField;public class User {@TableField("user_name")private String userName;// getter and setter
}
在上述例子中,userName
字段将映射到数据库表中的 user_name
字段。
2. exist
属性
exist
属性用于指定该字段是否在数据库表中存在。如果某个字段在数据库表中不存在,但又不想删除该字段,可以设置 exist = false
。
import com.baomidou.mybatisplus.annotation.TableField;public class User {@TableField(exist = false)private String temporaryData;// getter and setter
}
在上述例子中,temporaryData
字段在数据库表中不存在,但它仍然可以在实体类中使用。
3. fill
属性
fill
属性用于指定字段的填充策略。MyBatis-Plus提供了多种填充策略,例如在插入或更新时自动填充字段。
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import java.time.LocalDateTime;public class User {@TableField(fill = FieldFill.INSERT)private LocalDateTime createTime;// getter and setter
}
在上述例子中,createTime
字段将在插入记录时自动填充当前时间。
高级用法
1. 使用条件查询
通过 @TableField
注解,可以指定在查询条件中使用的SQL片段。常见的属性有 condition
。
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;public class User {@TableField(condition = "%s LIKE CONCAT('%%',#{%s},'%%')")private String email;// getter and setter
}// 使用示例
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("email", "example.com");
在上述例子中,email
字段在查询时使用了 LIKE
条件。
2. 字段加密和解密
在某些场景中,可能需要对字段进行加密存储和解密读取。可以通过自定义的类型处理器实现。
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.extension.handlers.EncryptHandler;public class User {@TableField(typeHandler = EncryptHandler.class)private String sensitiveData;// getter and setter