文章目录
MybatisPlus注解
1.@TableName
- 描述:表名注解
关于autoResultMap
的说明:
mp会自动构建一个ResultMap
并注入到mybatis里(一般用不上)。下面讲两句:因为mp底层是mybatis,所以一些mybatis的常识你要知道,mp只是帮你注入了常用crud到mybatis里 注入之前可以说是动态的(根据你entity的字段以及注解变化而变化),但是注入之后是静态的(等于你写在xml的东西) 而对于直接指定typeHandler
,mybatis只支持你写在2个地方:
- 定义在resultMap里,只作用于select查询的返回结果封装。
- 定义在
inser
t和update
sql的#{property}
里的property
后面(例:#{property,typehandler=xxx。xxx。xxx}
),只作用于设置值
而除了这两种直接指定typeHandler
,mybatis有一个全局的扫描你自己的ypeHandler
包的配置,这是根据你的property
的类型去找typeHandler
并使用。
问题
如果实体类是User而对应的表名t_user,如果这样去操作的话会报错(user这个表不存在),因为MybatisPlus 就是使用实体类名作为表名去操作数据库的这样会报错,当然如果出现这种情况可以使用@TableName
或者指定全局配置。
如果出现上述问题可以使用下面两种方式任选其一:
指定@TableName
注解
@Data
@TableName("t_user")
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
指定全局配置
mybatis-plus.global-config.db-config.table-prefix=t_
测试
@Test
public void contextLoads() {
List<User> users = userMapper.selectList(null);
users.forEach(user -> System.out.println(user));
}
测试结果
2.@TableId
- 描述:主键注解
IdType
3.@TableField
- 描述:字段注解(非主键)
关于jdbcType
和typeHandler
以及numericScale
的说明:
numericScale
只生效于 update 的sql。jdbcType
和typeHandler
如果不配合@TableName#autoResultMap = true
一起使用,也只生效于 update 的sql。 对于typeHandler
如果你的字段类型和set进去的类型为equals
关系,则只需要让你的typeHandler
让Mybatis加载到即可,不需要使用注解。
FieldStrategy
FieldFill
4.@Version
- 描述:乐观锁注解、标记 @Verison 在字段上
5.@EnumValue
- 描述:通枚举类注解(注解在枚举字段上)
6.@TableLogic
- 描述:表字段逻辑处理注解(逻辑删除)
7.@SqlParser
see @InterceptorIgnore
8.@KeySequence
- 描述:序列主键策略 oracle
- 属性:value、resultMap
9.@InterceptorIgnore
see 插件主体
MybatisPlusInterceptor
该插件是核心插件,目前代理了 Executor#query
和 Executor#update
和 StatementHandler#prepare
方法。
属性
private List<InnerInterceptor> interceptors = new ArrayList<>();
InnerInterceptor
我们提供的插件都将基于此接口来实现功能
目前已有的功能:
- 自动分页: PaginationInnerInterceptor
- 多租户: TenantLineInnerInterceptor
- 动态表名: DynamicTableNameInnerInterceptor
- 乐观锁: OptimisticLockerInnerInterceptor
- sql性能规范: IllegalSQLInnerInterceptor
- 防止全表更新与删除: BlockAttackInnerInterceptor
注意:
使用多个功能需要注意顺序关系,建议使用如下顺序
- 多租户,动态表名。
- 分页,乐观锁。
- sql性能规范,防止全表更新与删除。
总结:对sql进行单次改造的优先放入,不对sql进行改造的最后放入。
使用方式(以分页插件举例)
spring-boot
@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
拦截忽略注解 @InterceptorIgnore