网站建设设计ppt,在线动画手机网站模板,财务网站模板,帮助中心网站模板前言 这是我在这个网站整理的笔记#xff0c;关注我#xff0c;接下来还会持续更新。 作者#xff1a;神的孩子都在歌唱 mybatis-plus自动填充
大家做设计数据表的时候#xff0c;基本上都会有del_flag#xff0c;create_time, update_time,这三个字段#xff0c;这也是…前言 这是我在这个网站整理的笔记关注我接下来还会持续更新。 作者神的孩子都在歌唱 mybatis-plus自动填充
大家做设计数据表的时候基本上都会有del_flagcreate_time, update_time,这三个字段这也是表必备的三字段可是有一个问题我们每次做增改的时候都要写代码去定义一下这些字段的值这样会很麻烦目前有两种方法解决
sql可以自定义默认值也就是在建表的时候给字段设定默认值就可以了下面以pgsql为例 在代码里面写一个自动填充的功能相当于是写一个公共方法下面参考mybatis-plus mybati-plus帮我们实现了底层逻辑我们只需要自定义实现类MyMetaObjectHandler就可以了 mybatis-plush官网
自定义 MyMetaObjectHandler
Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {Overridepublic void insertFill(MetaObject metaObject) {try {//根据属性名字设置要填充的值if (metaObject.hasGetter(createTime)) {this.setFieldValByName(createTime, new Date(), metaObject);}//根据属性名字设置要填充的值if (metaObject.hasGetter(delFlag)) {this.strictInsertFill(metaObject,delFlag, String.class, 0);}} catch (Exception e) {throw new ServiceException(自动注入异常 e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);}}Overridepublic void updateFill(MetaObject metaObject) {try {if (metaObject.hasGetter(updateTime)) {this.setFieldValByName(updateTime, new Date(), metaObject);}} catch (Exception e) {throw new ServiceException(自动注入异常 e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);}}}
然后需要创建一个mybatis-plus配置类
EnableTransactionManagement(proxyTargetClass true)
Configuration
// 指定要扫描的Mapper类的包的路径
MapperScan(${mybatis-plus.mapperPackage})
public class MybatisPlusConfig {/*** 元对象字段填充控制器* https://baomidou.com/guide/auto-fill-metainfo.html*/Beanpublic MetaObjectHandler metaObjectHandler() {return new CreateAndUpdateMetaObjectHandler();}}
然后再注解填充字段 作者神的孩子都在歌唱 本人博客https://blog.csdn.net/weixin_46654114 转载说明务必注明来源附带本人博客连接。