Use a custom ID generator
- implementation
IdentifierGenerator
interface
@Component
public class CustomerIdGenerator implements IdentifierGenerator {
@Override
public Number nextId(Object entity) {
// Populate your own Id generator,
returnHolaSms.snowFlake(); }}Copy the code
- Fill in the id specified in an entity class or configuration file
- The configuration file
mybatis-plus:
global-config:
db-config:
id-type: assign_id
Copy the code
- Entity class
@TableId(type = IdType.ASSIGN_ID)
private Long id;
Copy the code
Select either of the two methods. If both methods are configured, the entity class prevails. If you set an ID manually in your code, it will take the one you set manually.
The fields
We create tables with create_user and update_user fields that are not relevant to the actual business, so we can specify how to fill the fields in advance and we don’t have to worry about the values of those fields.
- Write fill method, implementation
MetaObjectHandler
interface
This interface provides two methods, one at insert time and one at update time. We call the fill method parameters are: 1. Entity object, we can directly copy down 2. Name of the field to be filled 3. Type of the field to be filled 4
@Component
public class DataAutoFill implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createUser", String.class, HolaSms.currentUser());
this.strictInsertFill(metaObject, "updateUser", String.class, HolaSms.currentUser());
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "updateUser", String.class, HolaSms.currentUser()); }}Copy the code
- Annotate fields that need to be filled in
@TableField
Annotation, and specify the fill time.
/** * update person */ @tableField (fill = FieldFill.INSERT_UPDATE) private String updateUser; /** * create */ @tableField (fill = FieldFill.INSERT) private String createUser;Copy the code