SpringBoot整合Mybatis-plus

igxiaoshan Lv5

SpringBoot整合Mybatis-plus

@TableName注解

表名注解,用于标识实体类对应的表,作用于实体类

autoResultMap属性

autoResultMap: 是否自动构建resultMap,非必填,boolean类型,默认是false

ResultMapMybatis中用于映射查询结果的一个重要组件.当设置autoResultMap值为true时, Mybatis-plus会自动根据实体类的字段和数据库表的字段进行映射,生成相应的resultMap

keepGlobalPrefix属性

keepGlobalPrefix属性: 用于指定是否保留全局的表前缀

该属性通常和全局表前缀配置配合使用,以实现更灵活的表名配置

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
### yml配置全局表前缀
mybatis-plus:
global-config:
db-config:
table-prefix: sys_

// 实体类
@Data
@TableName(value = "teacher", keepGlobalPrefix = true)
public class TeacherEntity {

@TableId(value = "id", type = IdType.AUTO)
private Integer id;

private String name;

private int age;
}

-- 建表sql
CREATE TABLE `sys_teacher` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`name` varchar(255) DEFAULT NULL COMMENT '客户名称',
`age` int(11) DEFAULT NULL COMMENT '客户年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;

说明

  • 全局表前缀: 在全局配置中通过table-prefix设置全局表前缀为sys_
  • 实体类的@TableName注解: 在实体类中,通过value属性指定表名为teacher,再通过设置keepGlobalPrefix=true,表示要保留表前缀
  • 最终表名;通过全局表前缀配置和@TableName注解属性配合,最终的表名为sys_teacher

@TableId注解

@TableId: 作用于实体类主键字段;有两个属性

  • value: 主键字段别名,非必填
  • type: 指定主键类型,非必填,Eunm类型,默认是IdType.NONE

type属性

IdType

  • AUTO: 数据表ID自增
  • NONE: 无状态,该类型为未设置主键类型
  • INPUT: insert 自行 set 主键值
  • ASSIGN_ID: 分配 id,(主键类型为numer,long或者integer或者string),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
  • ASSIGN_UUID: 分配 UUID,主键类型为string,使用接口IdentifierGenerator的方法nextUUID
  • ID_WORKER: 分布式全局唯一 ID,长整型类型
  • UUID: 32位uuid字符串
  • ID_WORKER_STR: 分布式全局唯一 ID,字符串类型

@TableField注解

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/**
* 表字段标识
*
* @author hubin sjy tantan
* @since 2016-09-09
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface TableField {

/**
* 数据库字段值
* <p>
* 不需要配置该值的情况:
* <li> 当 {@link com.baomidou.mybatisplus.core.MybatisConfiguration#mapUnderscoreToCamelCase} 为 true 时,
* (mp下默认是true,mybatis默认是false), 数据库字段值.replace("_","").toUpperCase() == 实体属性名.toUpperCase() </li>
* <li> 当 {@link com.baomidou.mybatisplus.core.MybatisConfiguration#mapUnderscoreToCamelCase} 为 false 时,
* 数据库字段值.toUpperCase() == 实体属性名.toUpperCase() </li>
*/
String value() default "";

/**
* 是否为数据库表字段
* <p>
* 默认 true 存在,false 不存在
*/
boolean exist() default true;

/**
* 字段 where 实体查询比较条件
* <p>
* 默认 {@link SqlCondition#EQUAL}
*/
String condition() default "";

/**
* 字段 update set 部分注入, 该注解优于 el 注解使用
* <p>
* 例1:@TableField(.. , update="%s+1") 其中 %s 会填充为字段
* 输出 SQL 为:update 表 set 字段=字段+1 where ...
* <p>
* 例2:@TableField(.. , update="now()") 使用数据库时间
* 输出 SQL 为:update 表 set 字段=now() where ...
*/
String update() default "";

/**
* 字段验证策略之 insert: 当insert操作时,该字段拼接insert语句时的策略
* <p>
* IGNORED: 直接拼接 insert into table_a(column) values (#{columnProperty});
* NOT_NULL: insert into table_a(<if test="columnProperty != null">column</if>) values (<if test="columnProperty != null">#{columnProperty}</if>)
* NOT_EMPTY: insert into table_a(<if test="columnProperty != null and columnProperty!=''">column</if>) values (<if test="columnProperty != null and columnProperty!=''">#{columnProperty}</if>)
* NOT_EMPTY 如果针对的是非 CharSequence 类型的字段则效果等于 NOT_NULL
*
* @since 3.1.2
*/
FieldStrategy insertStrategy() default FieldStrategy.DEFAULT;

/**
* 字段验证策略之 update: 当更新操作时,该字段拼接set语句时的策略
* <p>
* IGNORED: 直接拼接 update table_a set column=#{columnProperty}, 属性为null/空string都会被set进去
* NOT_NULL: update table_a set <if test="columnProperty != null">column=#{columnProperty}</if>
* NOT_EMPTY: update table_a set <if test="columnProperty != null and columnProperty!=''">column=#{columnProperty}</if>
* NOT_EMPTY 如果针对的是非 CharSequence 类型的字段则效果等于 NOT_NULL
*
* @since 3.1.2
*/
FieldStrategy updateStrategy() default FieldStrategy.DEFAULT;

/**
* 字段验证策略之 where: 表示该字段在拼接where条件时的策略
* <p>
* IGNORED: 直接拼接 column=#{columnProperty}
* NOT_NULL: <if test="columnProperty != null">column=#{columnProperty}</if>
* NOT_EMPTY: <if test="columnProperty != null and columnProperty!=''">column=#{columnProperty}</if>
* NOT_EMPTY 如果针对的是非 CharSequence 类型的字段则效果等于 NOT_NULL
*
* @since 3.1.2
*/
FieldStrategy whereStrategy() default FieldStrategy.DEFAULT;

/**
* 字段自动填充策略
* <p>
* 在对应模式下将会忽略 insertStrategy 或 updateStrategy 的配置,等于断言该字段必有值
*/
FieldFill fill() default FieldFill.DEFAULT;

/**
* 是否进行 select 查询
* <p>
* 大字段可设置为 false 不加入 select 查询范围
*/
boolean select() default true;

/**
* 是否保持使用全局的 columnFormat 的值
* <p>
* 只生效于 既设置了全局的 columnFormat 也设置了上面 {@link #value()} 的值
* 如果是 false , 全局的 columnFormat 不生效
*
* @since 3.1.1
*/
boolean keepGlobalFormat() default false;

/**
* {@link ResultMapping#property} and {@link ParameterMapping#property}
*
* @since 3.4.4
*/
String property() default "";

/**
* JDBC类型 (该默认值不代表会按照该值生效),
* 只生效于 mp 自动注入的 method,
* 建议配合 {@link TableName#autoResultMap()} 一起使用
* <p>
* {@link ResultMapping#jdbcType} and {@link ParameterMapping#jdbcType}
*
* @since 3.1.2
*/
JdbcType jdbcType() default JdbcType.UNDEFINED;

/**
* 类型处理器 (该默认值不代表会按照该值生效),
* 只生效于 mp 自动注入的 method,
* 建议配合 {@link TableName#autoResultMap()} 一起使用
* <p>
* {@link ResultMapping#typeHandler} and {@link ParameterMapping#typeHandler}
*
* @since 3.1.2
*/
Class<? extends TypeHandler> typeHandler() default UnknownTypeHandler.class;

/**
* 只在使用了 {@link #typeHandler()} 时判断是否辅助追加 javaType
* <p>
* 一般情况下不推荐使用
* {@link ParameterMapping#javaType}
*
* @since 3.4.0 @2020-07-23
*/
boolean javaType() default false;

/**
* 指定小数点后保留的位数,
* 只生效于 mp 自动注入的 method,
* 建议配合 {@link TableName#autoResultMap()} 一起使用
* <p>
* {@link ParameterMapping#numericScale}
*
* @since 3.1.2
*/
String numericScale() default "";
}

condition属性

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 字段 where 实体查询比较条件
* <p>
* 默认 {@link SqlCondition#EQUAL}
*/
String condition() default "";

/**
* SQL 比较条件常量定义类
*
* @author hubin
* @since 2018-01-05
*/
public class SqlCondition {
/**
* 等于
*/
public static final String EQUAL = "%s=#{%s}";
/**
* 不等于
*/
public static final String NOT_EQUAL = "%s&lt;&gt;#{%s}";
/**
* % 两边 %
*/
public static final String LIKE = "%s LIKE CONCAT('%%',#{%s},'%%')";

/**
* % 两边 % [oracle使用]
*/
public static final String ORACLE_LIKE = "%s LIKE CONCAT(CONCAT('%%',#{%s}),'%%')";
/**
* % 左
*/
public static final String LIKE_LEFT = "%s LIKE CONCAT('%%',#{%s})";
/**
* 右 %
*/
public static final String LIKE_RIGHT = "%s LIKE CONCAT(#{%s},'%%')";
}

@Version注解

乐观锁 注解,作用于字段上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 乐观锁注解
* <p>
* 支持的字段类型:
* long,
* Long,
* int,
* Integer,
* java.util.Date,
* java.sql.Timestamp,
* java.time.LocalDateTime
*
* @author TaoYu
* @since 2016-01-23
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface Version {
}

使用前置工作

1
2
3
4
5
6
7
8
9
10
11
12
13
// 配置乐观锁配置
@EnableTransactionManagement
@Configuration
public class MyBatisPlusConfig {
// 注册乐观锁插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}

@OrderBy注解

MySQL指定排序,优先级低于wrapper条件查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 源码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface OrderBy {

/**
* 默认倒序,设置 true 顺序
*/
boolean asc() default false;

@Deprecated
boolean isDesc() default true;

/**
* 数字越小越靠前
*/
short sort() default Short.MAX_VALUE;

}

全局表前缀配置

1
2
3
4
5
## 配置数据表的统一前缀
mybatis-plus:
global-config:
db-config:
table-prefix: sys_

调试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// entity
@Data
public class Teacher {

@TableId(value = "id", type = IdType.AUTO)
private Integer id;

private String name;

private int age;
}

// sql
CREATE TABLE `sys_teacher` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`name` varchar(255) DEFAULT NULL COMMENT '客户名称',
`age` int(11) DEFAULT NULL COMMENT '客户年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;

// 测试 CRUD 功能

打印日志

1
2
3
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl