Skip to content

装载器

实体共有属性,在 新增、编辑 时统一的属性赋值操作

一般共有属性

  • 创建用户
  • 创建时间
  • 编辑用户
  • 编辑时间

在多数据库源时,不同库源的共有属性命名可能不同,也有可能有特有的属性,如下:

共有属性数据库1数据库2数据库3...
创建用户createBycreatorUser-...
创建时间createTimecreatorTime-...
编辑用户updateBy-lastModifyUser...
编辑时间updateTime-lastModifyTime...
创建标识-createFlag-...
编辑标识--updateFlag...

因此,增加业务自定义装载器,以实现不同库源使用不同的默认装载器

默认装载器

MybatisPlusMetaObjectHandler

框架默认的装载器

装载器注解

MetaHandler

  • 文件路径:ztgis-common包
  • 作用范围:实体类上
  • 未配置时,使用默认装载器
  • 本实体注解优先级高于继承的装载器
java
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MetaHandler {
    String value() default "";
}

注解使用示例

所有继承BizBaseEntity的实体都默认使用DemoConstant.META_FLAG标识的装载器,不存在则使用默认的

业务装载器

自定义业务装载器

java
@Slf4j
@Component
public class BizMyMetaObjectHandler implements MetaObjectHandler {


@Override
    public void insertFill(MetaObject metaObject) {
        UserProvider userProvider = SpringContext.getBean(UserProvider.class);
        UserInfo userInfo = userProvider.get();
        this.strictInsertFill(metaObject, "createBy", String.class, userInfo.getDepartmentName());
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
    }


@Override
    public void updateFill(MetaObject metaObject) {
        UserProvider userProvider = SpringContext.getBean(UserProvider.class);
        UserInfo userInfo = userProvider.get();
        this.setFieldValByName("updateBy", userInfo.getUserName(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

注入业务装载器

业务装载器的标识勿重复,重复将会相互覆盖

java
@Slf4j
@Configuration
public class BizMybatisPlusConfig {


//默认的装载器
    @Resource
    MybatisPlusMetaObjectHandler mybatisPlusMetaObjectHandler;


@PostConstruct
    public void init() {
        //注入业务装载器1
        mybatisPlusMetaObjectHandler.setMetaObjectHandler(DemoConstant.META_FLAG, new BizMyMetaObjectHandler());


//注入业务装载器2
//        mybatisPlusMetaObjectHandler.setMetaObjectHandler("test", new BizMyMetaObjectHandler());
    }
}

完整示例

  • 标识常量,以方便后续统一调整修改

常量

  • 业务库实体(继承自BizBaseEntity,使用DemoConstant.META_FLAG的装载器)

业务库实体

  • 业务库装载器

业务库装载器

  • 注入业务装载器

注入业务装载器

  • 接口调用

接口调用实体保存

  • 数据库结果

数据库结果