0
# Entity Annotations
1
2
MyBatis-Plus provides comprehensive annotation support for mapping Java entities to database tables, with flexible configuration options for table names, column mapping, primary key strategies, field validation, and special column handling.
3
4
## Capabilities
5
6
### Table Mapping Annotations
7
8
#### @TableName
9
10
Maps entity class to database table with schema and naming customization.
11
12
```java { .api }
13
@Target(ElementType.TYPE)
14
@Retention(RetentionPolicy.RUNTIME)
15
public @interface TableName {
16
/**
17
* Table name (default: class name converted to underscore)
18
*/
19
String value() default "";
20
21
/**
22
* Schema name
23
*/
24
String schema() default "";
25
26
/**
27
* Whether to keep global table prefix
28
*/
29
boolean keepGlobalPrefix() default false;
30
31
/**
32
* Custom result map name
33
*/
34
String resultMap() default "";
35
36
/**
37
* Whether to auto-build result map
38
*/
39
boolean autoResultMap() default false;
40
41
/**
42
* Exclude properties from automatic mapping
43
*/
44
String[] excludeProperty() default {};
45
}
46
```
47
48
#### @TableId
49
50
Configures primary key field mapping and generation strategy.
51
52
```java { .api }
53
@Target(ElementType.FIELD)
54
@Retention(RetentionPolicy.RUNTIME)
55
public @interface TableId {
56
/**
57
* Column name (default: field name converted to underscore)
58
*/
59
String value() default "";
60
61
/**
62
* Primary key generation type
63
*/
64
IdType type() default IdType.NONE;
65
}
66
```
67
68
#### @TableField
69
70
Configures field-to-column mapping with advanced options.
71
72
```java { .api }
73
@Target(ElementType.FIELD)
74
@Retention(RetentionPolicy.RUNTIME)
75
public @interface TableField {
76
/**
77
* Column name (default: field name converted to underscore)
78
*/
79
String value() default "";
80
81
/**
82
* Whether field exists in database table
83
*/
84
boolean exist() default true;
85
86
/**
87
* Custom condition for WHERE clause
88
*/
89
String condition() default "";
90
91
/**
92
* Custom update value
93
*/
94
String update() default "";
95
96
/**
97
* Insert strategy for field
98
*/
99
FieldStrategy insertStrategy() default FieldStrategy.DEFAULT;
100
101
/**
102
* Update strategy for field
103
*/
104
FieldStrategy updateStrategy() default FieldStrategy.DEFAULT;
105
106
/**
107
* WHERE condition strategy for field
108
*/
109
FieldStrategy whereStrategy() default FieldStrategy.DEFAULT;
110
111
/**
112
* Auto-fill strategy
113
*/
114
FieldFill fill() default FieldFill.DEFAULT;
115
116
/**
117
* Whether to include in SELECT queries
118
*/
119
boolean select() default true;
120
121
/**
122
* Whether to keep global column format
123
*/
124
boolean keepGlobalFormat() default false;
125
126
/**
127
* JDBC type for this field
128
*/
129
JdbcType jdbcType() default JdbcType.UNDEFINED;
130
131
/**
132
* Type handler class for this field
133
*/
134
Class<? extends TypeHandler> typeHandler() default UnknownTypeHandler.class;
135
136
/**
137
* Numeric scale for decimal types
138
*/
139
String numericScale() default "";
140
}
141
```
142
143
### Special Field Annotations
144
145
#### @Version
146
147
Marks field for optimistic locking version control.
148
149
```java { .api }
150
@Target(ElementType.FIELD)
151
@Retention(RetentionPolicy.RUNTIME)
152
public @interface Version {
153
}
154
```
155
156
#### @TableLogic
157
158
Configures logical delete functionality.
159
160
```java { .api }
161
@Target(ElementType.FIELD)
162
@Retention(RetentionPolicy.RUNTIME)
163
public @interface TableLogic {
164
/**
165
* Logical not deleted value (default: "")
166
*/
167
String value() default "";
168
169
/**
170
* Logical deleted value (default: "")
171
*/
172
String delval() default "";
173
}
174
```
175
176
#### @EnumValue
177
178
Marks enum field value to be stored in database.
179
180
```java { .api }
181
@Target(ElementType.FIELD)
182
@Retention(RetentionPolicy.RUNTIME)
183
public @interface EnumValue {
184
}
185
```
186
187
#### @KeySequence
188
189
Configures sequence-based key generation for Oracle, PostgreSQL, etc.
190
191
```java { .api }
192
@Target(ElementType.TYPE)
193
@Retention(RetentionPolicy.RUNTIME)
194
public @interface KeySequence {
195
/**
196
* Sequence name
197
*/
198
String value() default "";
199
200
/**
201
* Database type
202
*/
203
DbType dbType() default DbType.OTHER;
204
}
205
```
206
207
#### @OrderBy
208
209
Configures default ordering for entity queries.
210
211
```java { .api }
212
@Target(ElementType.FIELD)
213
@Retention(RetentionPolicy.RUNTIME)
214
public @interface OrderBy {
215
/**
216
* Whether to order ascending (default: true)
217
*/
218
boolean asc() default true;
219
220
/**
221
* Sort priority (smaller values have higher priority)
222
*/
223
short sort() default Short.MAX_VALUE;
224
}
225
```
226
227
### Interceptor Control Annotations
228
229
#### @InterceptorIgnore
230
231
Controls which interceptors to ignore for specific mapper methods.
232
233
```java { .api }
234
@Target({ElementType.METHOD, ElementType.TYPE})
235
@Retention(RetentionPolicy.RUNTIME)
236
public @interface InterceptorIgnore {
237
/**
238
* Ignore tenant line interceptor
239
*/
240
boolean tenantLine() default false;
241
242
/**
243
* Ignore dynamic table name interceptor
244
*/
245
boolean dynamicTableName() default false;
246
247
/**
248
* Ignore block attack interceptor
249
*/
250
boolean blockAttack() default false;
251
252
/**
253
* Ignore illegal SQL interceptor
254
*/
255
boolean illegalSql() default false;
256
257
/**
258
* Ignore data permission interceptor
259
*/
260
boolean dataPermission() default false;
261
}
262
```
263
264
## Enums
265
266
### IdType
267
268
Primary key generation strategies.
269
270
```java { .api }
271
public enum IdType {
272
/**
273
* Database auto-increment
274
*/
275
AUTO(0),
276
277
/**
278
* No primary key (used for views or tables without primary key)
279
*/
280
NONE(1),
281
282
/**
283
* User input ID (manual assignment)
284
*/
285
INPUT(2),
286
287
/**
288
* Assign ID using snowflake algorithm
289
*/
290
ASSIGN_ID(3),
291
292
/**
293
* Assign UUID
294
*/
295
ASSIGN_UUID(4);
296
}
297
```
298
299
### FieldFill
300
301
Auto-fill strategies for fields.
302
303
```java { .api }
304
public enum FieldFill {
305
/**
306
* Default - no auto-fill
307
*/
308
DEFAULT,
309
310
/**
311
* Fill on insert operations
312
*/
313
INSERT,
314
315
/**
316
* Fill on update operations
317
*/
318
UPDATE,
319
320
/**
321
* Fill on both insert and update operations
322
*/
323
INSERT_UPDATE;
324
}
325
```
326
327
### FieldStrategy
328
329
Field condition strategies for query building.
330
331
```java { .api }
332
public enum FieldStrategy {
333
/**
334
* Ignore validation (always include in conditions)
335
*/
336
IGNORED,
337
338
/**
339
* Ignore null values only
340
*/
341
NOT_NULL,
342
343
/**
344
* Ignore null and empty values
345
*/
346
NOT_EMPTY,
347
348
/**
349
* Use global default strategy
350
*/
351
DEFAULT,
352
353
/**
354
* Never include in conditions (used for read-only fields)
355
*/
356
NEVER;
357
}
358
```
359
360
## Usage Examples
361
362
**Basic Entity Mapping:**
363
364
```java
365
@TableName("sys_user")
366
public class User {
367
@TableId(type = IdType.AUTO)
368
private Long id;
369
370
@TableField("user_name")
371
private String name;
372
373
private Integer age;
374
375
@TableField("email_address")
376
private String email;
377
378
@TableField(fill = FieldFill.INSERT)
379
private LocalDateTime createTime;
380
381
@TableField(fill = FieldFill.INSERT_UPDATE)
382
private LocalDateTime updateTime;
383
384
// getters and setters...
385
}
386
```
387
388
**Advanced Field Configuration:**
389
390
```java
391
@TableName("product")
392
public class Product {
393
@TableId(type = IdType.ASSIGN_ID)
394
private Long id;
395
396
private String name;
397
398
@TableField(value = "price_amount", jdbcType = JdbcType.DECIMAL, numericScale = "2")
399
private BigDecimal price;
400
401
@TableField(insertStrategy = FieldStrategy.NOT_EMPTY, updateStrategy = FieldStrategy.NOT_NULL)
402
private String description;
403
404
@TableField(exist = false) // Not a database column
405
private String displayName;
406
407
@TableField(select = false) // Exclude from SELECT queries by default
408
private String internalNotes;
409
410
@TableLogic
411
private Integer deleted; // 0 = not deleted, 1 = deleted
412
413
@Version
414
private Integer version; // For optimistic locking
415
416
// getters and setters...
417
}
418
```
419
420
**Enum Handling:**
421
422
```java
423
public enum UserStatus {
424
ACTIVE(1, "Active"),
425
INACTIVE(0, "Inactive"),
426
SUSPENDED(-1, "Suspended");
427
428
@EnumValue // This field will be stored in database
429
private final int code;
430
private final String description;
431
432
UserStatus(int code, String description) {
433
this.code = code;
434
this.description = description;
435
}
436
437
// getters...
438
}
439
440
@TableName("user")
441
public class User {
442
@TableId(type = IdType.AUTO)
443
private Long id;
444
445
private String name;
446
447
private UserStatus status; // Will store code (1, 0, -1) in database
448
449
// getters and setters...
450
}
451
```
452
453
**Auto-Fill Configuration:**
454
455
```java
456
@Component
457
public class MyMetaObjectHandler implements MetaObjectHandler {
458
459
@Override
460
public void insertFill(MetaObject metaObject) {
461
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
462
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
463
this.strictInsertFill(metaObject, "createUser", String.class, getCurrentUser());
464
this.strictInsertFill(metaObject, "updateUser", String.class, getCurrentUser());
465
}
466
467
@Override
468
public void updateFill(MetaObject metaObject) {
469
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
470
this.strictUpdateFill(metaObject, "updateUser", String.class, getCurrentUser());
471
}
472
473
private String getCurrentUser() {
474
// Get current user from security context
475
return "system"; // Placeholder
476
}
477
}
478
479
// Entity with auto-fill fields
480
@TableName("audit_entity")
481
public class AuditEntity {
482
@TableId(type = IdType.AUTO)
483
private Long id;
484
485
@TableField(fill = FieldFill.INSERT)
486
private LocalDateTime createTime;
487
488
@TableField(fill = FieldFill.INSERT_UPDATE)
489
private LocalDateTime updateTime;
490
491
@TableField(fill = FieldFill.INSERT)
492
private String createUser;
493
494
@TableField(fill = FieldFill.INSERT_UPDATE)
495
private String updateUser;
496
497
// getters and setters...
498
}
499
```
500
501
**Schema and Naming Configuration:**
502
503
```java
504
@TableName(value = "user_profile", schema = "auth")
505
public class UserProfile {
506
@TableId(type = IdType.AUTO)
507
private Long id;
508
509
@TableField("first_name")
510
private String firstName;
511
512
@TableField("last_name")
513
private String lastName;
514
515
// Maps to column: auth.user_profile.first_name, auth.user_profile.last_name
516
517
// getters and setters...
518
}
519
```
520
521
**Custom Type Handlers:**
522
523
```java
524
public class JsonTypeHandler extends AbstractJsonTypeHandler<List<String>> {
525
@Override
526
protected List<String> parse(String json) {
527
return JSON.parseArray(json, String.class);
528
}
529
530
@Override
531
protected String toJson(List<String> obj) {
532
return JSON.toJSONString(obj);
533
}
534
}
535
536
@TableName("user_preferences")
537
public class UserPreferences {
538
@TableId(type = IdType.AUTO)
539
private Long id;
540
541
@TableField(typeHandler = JsonTypeHandler.class)
542
private List<String> tags; // Stored as JSON string in database
543
544
@TableField(typeHandler = JacksonTypeHandler.class)
545
private Map<String, Object> settings; // Stored as JSON using Jackson
546
547
// getters and setters...
548
}
549
```
550
551
**Sequence-Based Primary Keys:**
552
553
```java
554
@TableName("oracle_entity")
555
@KeySequence(value = "SEQ_ORACLE_ENTITY", dbType = DbType.ORACLE)
556
public class OracleEntity {
557
@TableId(type = IdType.INPUT) // Use INPUT for sequence-generated IDs
558
private Long id;
559
560
private String name;
561
562
// getters and setters...
563
}
564
565
@TableName("postgres_entity")
566
@KeySequence(value = "postgres_entity_id_seq", dbType = DbType.POSTGRE_SQL)
567
public class PostgresEntity {
568
@TableId(type = IdType.INPUT)
569
private Long id;
570
571
private String name;
572
573
// getters and setters...
574
}
575
```
576
577
**Interceptor Control:**
578
579
```java
580
@Mapper
581
public interface UserMapper extends BaseMapper<User> {
582
583
@InterceptorIgnore(tenantLine = true, dataPermission = true)
584
List<User> selectAllUsers();
585
586
@InterceptorIgnore(blockAttack = true)
587
int deleteAllTestUsers();
588
}
589
```
590
591
**Complex Entity Example:**
592
593
```java
594
@TableName(value = "complex_entity", resultMap = "complexEntityResultMap")
595
public class ComplexEntity {
596
@TableId(type = IdType.ASSIGN_ID)
597
private Long id;
598
599
@TableField(condition = SqlCondition.LIKE)
600
private String name;
601
602
@TableField(updateStrategy = FieldStrategy.IGNORED)
603
private String code;
604
605
@TableField(whereStrategy = FieldStrategy.NOT_EMPTY)
606
private String description;
607
608
@TableField(update = "now()")
609
private LocalDateTime lastModified;
610
611
@TableLogic(value = "0", delval = "1")
612
private Integer isDeleted;
613
614
@Version
615
private Integer version;
616
617
@OrderBy(asc = false, sort = 1)
618
private LocalDateTime createTime;
619
620
@OrderBy(asc = true, sort = 2)
621
private String name;
622
623
@TableField(exist = false)
624
private List<String> tags; // Calculated field, not in database
625
626
// getters and setters...
627
}
628
```
629
630
**Global Configuration:**
631
632
```java
633
@Configuration
634
public class MybatisPlusConfig {
635
636
@Bean
637
public GlobalConfig globalConfig() {
638
GlobalConfig globalConfig = new GlobalConfig();
639
GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
640
641
// Global ID strategy
642
dbConfig.setIdType(IdType.ASSIGN_ID);
643
644
// Global table prefix
645
dbConfig.setTablePrefix("t_");
646
647
// Global logical delete configuration
648
dbConfig.setLogicDeleteField("is_deleted");
649
dbConfig.setLogicDeleteValue("1");
650
dbConfig.setLogicNotDeleteValue("0");
651
652
// Global field strategies
653
dbConfig.setInsertStrategy(FieldStrategy.NOT_NULL);
654
dbConfig.setUpdateStrategy(FieldStrategy.NOT_NULL);
655
dbConfig.setWhereStrategy(FieldStrategy.NOT_EMPTY);
656
657
// Column naming strategy
658
dbConfig.setTableUnderline(true);
659
dbConfig.setColumnUnderline(true);
660
661
globalConfig.setDbConfig(dbConfig);
662
return globalConfig;
663
}
664
665
@Bean
666
public MetaObjectHandler metaObjectHandler() {
667
return new MyMetaObjectHandler();
668
}
669
}
670
```
671
672
This annotation system provides flexible and powerful entity mapping capabilities while maintaining clean separation between Java objects and database schemas.