一般在表設計的時候,都會在表中添加一些系統字段,比如 create_time
、update_time
等。
阿里巴巴開發手冊中也有這樣的提示,如果對於這些公共字段可以進行統一處理,不需要每次進行插入或者更新操作的時候 set
一下,就可以提高開發效率,解放雙手。
加入依賴
下面就通過 MyBatis Plus 來完成字段自動填充,首先加入 MyBatis Plus 依賴:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
創建實體類,添加填充註解
創建一個實體類,然後在需要自動填充的屬性上加註解 @TableField(fill = FieldFill.INSERT)
、@TableField(fill = FieldFill.INSERT_UPDATE)
等註解。
@Data
@TableName("user")
public class UserEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 主鍵
*/
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
/**
* 姓名
*/
@TableField("name")
private String name;
/**
* 年齡
*/
@TableField("age")
private Integer age;
/**
* 郵件
*/
@TableField("email")
private String email;
/**
* 創建時間
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
public Date createTime;
/**
* 修改時間
*/
@TableField(value = "modify_time", fill = FieldFill.INSERT_UPDATE)
public Date modifyTime;
}
其中 fill 屬性爲字段自動填充策略,可選的參數如下所示:
public enum FieldFill {
/**
* 默認不處理
*/
DEFAULT,
/**
* 插入填充字段
*/
INSERT,
/**
* 更新填充字段
*/
UPDATE,
/**
* 插入和更新填充字段
*/
INSERT_UPDATE
}
就直接創建一個 Mapper,來便於測試:
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
}
實現元對象處理器接口
MyBatis Plus 版本不同,實現方式可能會有些許不同,在 3.4.1 版本是實現 MetaObjectHandler 接口,低版本可能是繼承 MetaObjectHandler 抽象類,來實現對應的方法。
下面爲實現插入和更新數據的字段填充邏輯,在插入對象時,對創建時間 createTime
和修改時間 modifyTime
字段自動填充爲當前時間,在更新對象時,將修改時間 modifyTime
修改爲最新時間。
@Component
public class CommonMetaObjectHandler implements MetaObjectHandler {
/**
* 創建時間
*/
private static final String FIELD_SYS_CREATE_TIME = "createTime";
/**
* 修改時間
*/
private static final String FIELD_SYS_MODIFIED_TIME = "modifyTime";
/**
* 插入元對象字段填充(用於插入時對公共字段的填充)
*
* @param metaObject 元對象
*/
@Override
public void insertFill(MetaObject metaObject) {
Date currentDate = new Date();
// 插入創建時間
if (metaObject.hasSetter(FIELD_SYS_CREATE_TIME)) {
this.strictInsertFill(metaObject, FIELD_SYS_CREATE_TIME, Date.class, currentDate);
}
// 同時設置修改時間爲當前插入時間
if (metaObject.hasSetter(FIELD_SYS_MODIFIED_TIME)) {
this.strictUpdateFill(metaObject, FIELD_SYS_MODIFIED_TIME, Date.class, currentDate);
}
}
/**
* 更新元對象字段填充(用於更新時對公共字段的填充)
*
* @param metaObject 元對象
*/
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName(FIELD_SYS_MODIFIED_TIME, new Date(), metaObject);
}
}
其中,默認填充策略爲默認有值不覆蓋,如果提供的值爲 null
也不填充。如果默認填充策略不滿足,可以重寫 strictFillStrategy
方法以滿足自己的需求。
測試字段自動填充
編寫測試類來檢驗是否在插入和更新操作時,是否會自動填充響應的字段。
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class AutoFillTest {
@Resource
private UserMapper userMapper;
@Test
public void test() throws InterruptedException {
UserEntity user = new UserEntity();
user.setName("wupx");
user.setAge(18);
user.setEmail("[email protected]");
userMapper.insert(user);
Long id = user.getId();
UserEntity beforeUser = userMapper.selectById(id);
log.info("before user:{}", beforeUser);
Assert.assertNotNull(beforeUser.getCreateTime());
Assert.assertNotNull(beforeUser.getModifyTime());
beforeUser.setAge(19);
Thread.sleep(1000L);
userMapper.updateById(beforeUser);
log.info("query user:{}", userMapper.selectById(id));
// 清除測試數據
userMapper.deleteById(id);
}
}
啓動測試類,通過日誌可以看出來:
before user:UserEntity(id=1346071927831134210, name=wupx, age=18, [email protected], createTime=Mon Jan 04 20:32:11 CST 2021, modifyTime=Mon Jan 04 20:32:11 CST 2021)
query user:UserEntity(id=1346071927831134210, name=wupx, age=19, [email protected], createTime=Mon Jan 04 20:32:11 CST 2021, modifyTime=Mon Jan 04 20:32:13 CST 2021)
第一次插入對象的時候,創建時間和修改時間都自動填充了,當修改對象的時候,修改時間也相應的進行了更新。
另外可以將公共字段封裝到公共類中,比如 BaseEntity
:
@Data
public class BaseEntity {
/**
* 主鍵
*/
@TableId(value = "id", type = IdType.ASSIGN_UUID)
private Long id;
/**
* 創建時間
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
/**
* 修改時間
*/
@TableField(value = "modify_time", fill = FieldFill.INSERT_UPDATE)
private Date modifyTime;
}
經過測試,也是可以完成公共字段的自動填充,大家也可以在項目中這樣搞下,可以減少每次插入或者更新時的 set
操作。
總結
本文的完整代碼在 https://github.com/wupeixuan/SpringBoot-Learn
的 mybatis-plus-auto-fill-metainfo
目錄下。
你有沒有經常需要去設置公共字段的煩惱呢,如果有這種情況,可以通過這種方式來解決下。
「最好的關係就是互相成就」,大家的「點贊、在看、分享、留言」就是我創作的最大動力。
❝參考
https://github.com/wupeixuan/SpringBoot-Learn
https://baomidou.com/guide/auto-fill-metainfo.html
❞
本文分享自微信公衆號 - 武培軒(wupeixuan404)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。