下面对MyBatis-Plus
提供的注解进行整理。
官方文档 传送门
@TableName
用于指定表名,作用在实体类上面。
常用的属性:
value
—— 表名
例子:
@TableName("tb_user")
public class UserEntity {
...
}
@TableId
用于指定表的主键名。
常用属性:
value
—— 主键名type
—— 主键类型
其中,主键类型type
默认值是IdType.NONE
,取值有以下几种:
IdType.AUTO
—— 主键自增,系统分配,不需要手动输入。IdType.NONE
—— 未设置主键。IdType.INPUT
—— 需要自己设置主键值。IdType.ASSIGN_ID
—— 当主键类型是Long
、Integer
、String
时,系统调用IdentifierGenerator.nextId()
自动分配,默认是雪花算法。IdType.ASSIGN_UUID
—— 分配UUID
,主键类型为String
,系统调用IdentifierGenerator.nextUUID()
方法。
例子:
@TableId(value = "user_id", type = IdType.ASSIGN_ID)
private Long id;
@TableField
用于指定表的非主键字段名。
常用属性:
value
—— 指定非主键字段名。exist
—— 用于指明是否是数据库表中的字段,true
是,false
不是。fill
—— 用于指定字段填充策略。
字段填充策略(一般用于填充创建时间、修改时间等字段)如下:
FieldFill.DEFAULT
—— 默认不填充。FieldFill.INSERT
—— 插入时填充。FieldFill.UPDATE
—— 更新时填充。FieldFill.INSERT_UPDATE
—— 插入、更新时填充。
注意:需要实现自定义的填充器,字段填充策略才会生效。具体详见 传送门
例子:
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@Version
用于标记实现乐观锁的表字段。
例子:
@Version
private Integer version;
@EnumValue
只能标记在枚举类的字段上,表示数据库填入的值是枚举类中的哪个字段的值。
例子:
@Data
@TableName("tb_student")
public class Student {
private Integer id;
private String name;
// 在数据库中,grade字段的类型是int,所以需要在GradeEnum中使用@EnumValue注解取值的字段
private GradeEnum grade;
}
public enum GradeEnum {
PRIMARY(1, "小学"),
SECONDORY(2, "中学"),
HIGH(3, "高中");
@EnumValue
private int code;
private String name;
...
}
@TableLogic
用于标记表示逻辑删除的字段。
使用了这个注解,在调用删除方法的时候并不会真的删除数据,而是更新数据,设置逻辑删除字段的值。
常用属性:
value
—— 指定逻辑未删除时候的值。delval
—— 指定逻辑删除时候的值。
例子:
@TableField("delete_flag")
@TableLogic(value = "0", delval = "-1")
private Integer deleteFlag;