mybatis-plus自动填充创建人id
时间: 2023-07-01 18:22:40 浏览: 60
可以通过实现 `MetaObjectHandler` 接口来实现自动填充创建人id。具体步骤如下:
1. 创建一个类实现 `MetaObjectHandler` 接口,实现 `insertFill` 方法:
```java
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createUserId", String.class, getCurrentUserId());
}
@Override
public void updateFill(MetaObject metaObject) {
// 更新时不需要填充
}
private String getCurrentUserId() {
// 获取当前登录用户的id,可以从ThreadLocal等地方获取
return "123";
}
}
```
2. 在需要自动填充的实体类中,添加 `@TableField` 注解,设置 `fill = FieldFill.INSERT`:
```java
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
@TableField(fill = FieldFill.INSERT)
private String createUserId;
}
```
这样,在插入数据时,`createUserId` 字段就会自动填充为当前登录用户的id。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)