Spring Boot 集成 Mybatis Plus 自動填充字段的實例詳解
一般在表設(shè)計的時候,都會在表中添加一些系統(tǒng)字段,比如 create_time、update_time等。
阿里巴巴開發(fā)手冊中也有這樣的提示,如果對于這些公共字段可以進(jìn)行統(tǒng)一處理,不需要每次進(jìn)行插入或者更新操作的時候 set 一下,就可以提高開發(fā)效率,解放雙手。
加入依賴下面就通過 MyBatis Plus 來完成字段自動填充,首先加入 MyBatis Plus 依賴:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version></dependency>創(chuàng)建實體類,添加填充注解
創(chuàng)建一個實體類,然后在需要自動填充的屬性上加注解 @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; /** * 創(chuàng)建時間 */ @TableField(value = 'create_time', fill = FieldFill.INSERT) public Date createTime; /** * 修改時間 */ @TableField(value = 'modify_time', fill = FieldFill.INSERT_UPDATE) public Date modifyTime;}
其中 fill 屬性為字段自動填充策略,可選的參數(shù)如下所示:
public enum FieldFill { /** * 默認(rèn)不處理 */ DEFAULT, /** * 插入填充字段 */ INSERT, /** * 更新填充字段 */ UPDATE, /** * 插入和更新填充字段 */ INSERT_UPDATE}
就直接創(chuàng)建一個 Mapper,來便于測試:
@Mapperpublic interface UserMapper extends BaseMapper<UserEntity> {}
實現(xiàn)元對象處理器接口
MyBatis Plus 版本不同,實現(xiàn)方式可能會有些許不同,在 3.4.1 版本是實現(xiàn) MetaObjectHandler 接口,低版本可能是繼承 MetaObjectHandler 抽象類,來實現(xiàn)對應(yīng)的方法。
下面為實現(xiàn)插入和更新數(shù)據(jù)的字段填充邏輯,在插入對象時,對創(chuàng)建時間 createTime 和修改時間 modifyTime 字段自動填充為當(dāng)前時間,在更新對象時,將修改時間 modifyTime 修改為最新時間。
@Componentpublic class CommonMetaObjectHandler implements MetaObjectHandler { /** * 創(chuàng)建時間 */ 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();// 插入創(chuàng)建時間if (metaObject.hasSetter(FIELD_SYS_CREATE_TIME)) { this.strictInsertFill(metaObject, FIELD_SYS_CREATE_TIME, Date.class, currentDate);}// 同時設(shè)置修改時間為當(dāng)前插入時間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); }}
其中,默認(rèn)填充策略為默認(rèn)有值不覆蓋,如果提供的值為 null 也不填充。如果默認(rèn)填充策略不滿足,可以重寫 strictFillStrategy 方法以滿足自己的需求。
測試字段自動填充編寫測試類來檢驗是否在插入和更新操作時,是否會自動填充響應(yīng)的字段。
@Slf4j@RunWith(SpringRunner.class)@SpringBootTestpublic class AutoFillTest { @Resource private UserMapper userMapper; @Test public void test() throws InterruptedException {UserEntity user = new UserEntity();user.setName('wupx');user.setAge(18);user.setEmail('wupx@qq.com');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));// 清除測試數(shù)據(jù)userMapper.deleteById(id); }}
啟動測試類,通過日志可以看出來:
before user:UserEntity(id=1346071927831134210, name=wupx, age=18, email=wupx@qq.com, 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=wupx@qq.com, createTime=Mon Jan 04 20:32:11 CST 2021, modifyTime=Mon Jan 04 20:32:13 CST 2021)
第一次插入對象的時候,創(chuàng)建時間和修改時間都自動填充了,當(dāng)修改對象的時候,修改時間也相應(yīng)的進(jìn)行了更新。
另外可以將公共字段封裝到公共類中,比如 BaseEntity:
@Datapublic class BaseEntity { /** * 主鍵 */ @TableId(value = 'id', type = IdType.ASSIGN_UUID) private Long id; /** * 創(chuàng)建時間 */ @TableField(value = 'create_time', fill = FieldFill.INSERT) private Date createTime; /** * 修改時間 */ @TableField(value = 'modify_time', fill = FieldFill.INSERT_UPDATE) private Date modifyTime;}
經(jīng)過測試,也是可以完成公共字段的自動填充,大家也可以在項目中這樣搞下,可以減少每次插入或者更新時的 set 操作。
總結(jié)本文的完整代碼在 https://github.com/wupeixuan/SpringBoot-Learn 的 mybatis-plus-auto-fill-metainfo 目錄下。
你有沒有經(jīng)常需要去設(shè)置公共字段的煩惱呢,如果有這種情況,可以通過這種方式來解決下。
❝參考
https://github.com/wupeixuan/SpringBoot-Learn
https://baomidou.com/guide/auto-fill-metainfo.html
到此這篇關(guān)于Spring Boot 集成 Mybatis Plus 自動填充字段的文章就介紹到這了,更多相關(guān)Spring Boot 集成 Mybatis Plus 填充字段內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
