> 文章列表 > 4.mybatis-plus-常用注解

4.mybatis-plus-常用注解

4.mybatis-plus-常用注解

1.@TableName

  • 描述:表名注解,标识实体类对应的表
  • 使用位置:实体类

将数据库中user表更名为mp_user

@TableName("mp_user")
public class User {private Long id;private String name;private Integer age;private String email;
}# 或者配置mybatis-plus全局配置
mybatis-plus:configuration:# 日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl#开启映射时驼峰命名map-underscore-to-camel-case: true# 设置mybatis-plus全局配置global-config:db-config:# 设置表名前缀table-prefix: mp_

参数说明

属性 类型 必须指定 默认值 描述
value String “” 表名
schema String “” schema
keepGlobalPrefix boolean false 是否保持使用全局的 tablePrefix 的值(当全局 tablePrefix 生效时)
resultMap String “” xml 中 resultMap 的 id(用于满足特定类型的实体类对象绑定)
autoResultMap boolean false 是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建与注入)
excludeProperty String[] {} 需要排除的属性名 @since 3.3.1

关于 autoResultMap 的说明:

MP会自动构建一个 resultMap 并注入到 MyBatis 里(一般用不上),请注意以下内容:

因为 MP 底层是 MyBatis,所以 MP 只是帮您注入了常用 CRUDMyBatis 里,注入之前是动态的(根据您的 Entity 字段以及注解变化而变化),但是注入之后是静态的(等于 XML 配置中的内容)。

而对于 typeHandler 属性,MyBatis 只支持写在 2 个地方:

  1. 定义在 resultMap 里,作用于查询结果的封装
  2. 定义在 insertupdate 语句的 #{property} 中的 property 后面(例:#{property,typehandler=xxx.xxx.xxx}),并且只作用于当前 设置值

除了以上两种直接指定 typeHandler 的形式,MyBatis 有一个全局扫描自定义 typeHandler 包的配置,原理是根据您的 property 类型去找其对应的 typeHandler 并使用。

2.@TableId

  • 描述:主键注解
  • 使用位置:实体类主键字段

mp_user表中id字段更改uidmybatis-plus默认主键字段为id,不是id的话需要指定添加@TableId注解指定为主键

public class User {# 将字段uid映射为id,将数据库中设置为自增可以使用IdType@TableId(value = "uid",type = IdType.AUTO)private Long  id;private String name;private Integer age;private String email;
}

默认自增为雪花算法,可通过注解@TableId实现,也可以通过全局配置配置主键生成策略

mybatis-plus:
global-config:db-config:# 设置统一的主键生成策略id-type: auto

参数说明

属性 类型 必须指定 默认值 描述
value String “” 主键字段名
type Enum IdType.ASSIGN_ID 指定主键类

1.@IdType

描述
AUTO 数据库 ID 自增
NONE 无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
INPUT insert 前自行 set 主键值
ASSIGN_ID 分配 ID(主键类型为 Number(Long 和 Integer)或 String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID 分配 UUID,主键类型为 String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认 default 方法)
ID_WORKER 分布式全局唯一 ID 长整型类型(please use ASSIGN_ID)
UUID 32 位 UUID 字符串(please use ASSIGN_UUID)
ID_WORKER_STR 分布式全局唯一 ID 字符串类型(please use ASSIGN_ID)

3.@TableField

  • 描述:字段注解(非主键)

mp_user表中name字段更改user_name,添加@TableField注解将user_name映射为name

@TableName("mp_user")
public class User {@TableIdprivate Long id;@TableField("user_name")private String name;private Integer age;private String email;
}

参数说明

属性 类型 必须指定 默认值 描述
value String “” 数据库字段名
exist boolean true 是否为数据库表字段
condition String “” 字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s},参考(opens new window)
update String “” 字段 update set 部分注入,例如:当在version字段上注解update="%s+1" 表示更新时会 set version=version+1 (该属性优先级高于 el 属性)
insertStrategy Enum FieldStrategy.DEFAULT 举例:NOT_NULL insert into table_a(<if test="columnProperty != null">column</if>) values (<if test="columnProperty != null">#{columnProperty}</if>)
updateStrategy Enum FieldStrategy.DEFAULT 举例:IGNORED update table_a set column=#{columnProperty}
whereStrategy Enum FieldStrategy.DEFAULT 举例:NOT_EMPTY where <if test="columnProperty != null and columnProperty!=''">column=#{columnProperty}</if>
fill Enum FieldFill.DEFAULT 字段自动填充策略
select boolean true 是否进行 select 查询
keepGlobalFormat boolean false 是否保持使用全局的 format 进行处理
jdbcType JdbcType JdbcType.UNDEFINED JDBC 类型 (该默认值不代表会按照该值生效)
typeHandler Class<? extends TypeHandler> UnknownTypeHandler.class 类型处理器 (该默认值不代表会按照该值生效)
numericScale String “” 指定小数点后保留的位数

关于jdbcTypetypeHandler以及numericScale的说明:

numericScale只生效于 update 的 sql. jdbcTypetypeHandler如果不配合@TableName#autoResultMap = true一起使用,也只生效于 update 的 sql. 对于typeHandler如果你的字段类型和 set 进去的类型为equals关系,则只需要让你的typeHandler让 Mybatis 加载到即可,不需要使用注解

1.@ieldStrategy

描述
IGNORED 忽略判断
NOT_NULL 非 NULL 判断
NOT_EMPTY 非空判断(只对字符串类型字段,其他类型字段依然为非 NULL 判断)
DEFAULT 追随全局配置
NEVER 不加入SQL

2.FieldFill

描述
DEFAULT 默认不处理
INSERT 插入时填充字段
UPDATE 更新时填充字段
INSERT_UPDATE 插入和更新时填充字段

实现元对象处理器接口

@Data
public class User {......@TableField(value="create_time",fill = FieldFill.INSERT)private Date createTime;@TableField(value="update_time",fill = FieldFill.INSERT_UPDATE)private Date updateTime;
}@Component
public class MyObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {//添加时填充的数据......this.setFieldValByName("createTime", new Date(), metaObject);this.setFieldValByName("updateTime", new Date(), metaObject);}
}

4.@Version

  • 描述:乐观锁注解、标记 @Version 在字段上

*数据库中添加version字段*

ALTER TABLE `user` ADD COLUMN `version` INT

实体类添加version字段并添加 @Version 注解

    @Version@TableField(fill = FieldFill.INSERT)private Integer version;

元对象处理器接口添加version的insert默认值

@Component
public class MyObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {//添加时填充的数据......this.setFieldValByName("version", 1, metaObject);}
}

特别说明:

  • 支持的数据类型只有 int,Integer,long,Long,Date,Timestamp,LocalDateTime

  • 整数类型下 newVersion = oldVersion + 1

  • newVersion 会回写到 entity

  • 仅支持 updateById(id)update(entity, wrapper) 方法

    update(entity, wrapper) 方法下, wrapper 不能复用!!!

在 MybatisPlusConfig 中注册 Bean

创建配置类

@EnableTransactionManagement
@Configuration
@MapperScan("com.atguigu.mybatis_plus.mapper")
public class MyOptimisticLockerInterceptor {/*** 乐观锁插件*/@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor() {return new OptimisticLockerInterceptor();}
}
# 测试/*** 测试 乐观锁插件*/
@Test
public void testOptimisticLocker() {//查询User user = userMapper.selectById(1L);//修改数据user.setName("Helen Yao");user.setEmail("helen@qq.com");//执行更新userMapper.updateById(user);
}

5.@EnumValue

  • 描述:普通枚举类注解(注解在枚举字段上)

6.@TableLogic

  • 描述:表字段逻辑处理注解(逻辑删除)
属性 类型 必须指定 默认值 描述
value String “” 逻辑未删除值
delval String “” 逻辑删除值

数据库中添加 deleted字段

手动添加在数据库中可添加字段`is_deleted`,数据类型为`int`,默认值为`0`
# 或
ALTER TABLE `user` ADD COLUMN `deleted` boolean

实体类添加deleted字段

并加上 @TableLogic 注解 和 @TableField(fill = FieldFill.INSERT) 注解

    @TableLogic@TableField(fill = FieldFill.UPDATE)private Integer isDeleted;

元对象处理器接口添加deleted的insert默认值

@Component
public class MyObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {//添加时填充的数据//0-未删除  1-已删除......this.setFieldValByName("is_deleted", 0, metaObject);}
}@Component
public class MpInterceptor {/*** 创建乐观锁拦截器,存入Spring容器* 拦截生成的sql语句,注入版本号的字段*/@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor() {return new OptimisticLockerInterceptor();}
}

全局配置

mybatis-plus:global-config:db-config:# versionlogic-delete-field: is_deleted # 全局逻辑删除的实体字段名logic-delete-value: 1 # 逻辑已删除值(默认为 1)logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

7.@KeySequence

  • 描述:序列主键策略 oracle
  • 属性:value、dbType
属性 类型 必须指定 默认值 描述
value String “” 序列名
dbType Enum DbType.OTHER 数据库类型,未配置默认使用注入 IKeyGenerator 实现,多个实现必须指定

8.@InterceptorIgnore

  • value 值为 1 | yes | on 视为忽略,例如 @InterceptorIgnore(tenantLine = "1")
  • value 值为 0 | false | off | 空值不变 视为正常执行。

9.@OrderBy

  • 描述:内置 SQL 默认指定排序,优先级低于 wrapper 条件查询
属性 类型 必须指定 默认值 描述
isDesc boolean true 是否倒序查询
sort short Short.MAX_VALUE 数字越小越靠前