mybatis-mapper / mapper

MyBatis Mapper
https://mapper.mybatis.io
Apache License 2.0
325 stars 47 forks source link

springboot @EnableScheduling开启定时任务activerecord模式报错 #51

Closed ChengSense closed 1 year ago

ChengSense commented 1 year ago

springboot @EnableScheduling开启定时任务activerecord模式第一次报错,错误内容java.lang.RuntimeException: com.cytech.framework.db.entity.BusConsult Mapper interface not found,BusConsultMapper是存在的,第二次执行就好了。 业务代码如下:

@SpringBootApplication
@EnableDiscoveryClient
@MapperScan({"com.xxxx.framework.db.mapper", "com.xxxx.task.dao"})
@EnableFeignClients("com.xxxx.framework.feign")
@EnableScheduling
public class HealthTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(HealthTaskApplication.class);
    }
}

@Component
public class SystemDealConsultTask{

    @Scheduled(fixedDelay = 5 * 1000)
    public void run() {
        List<BusConsult> busConsultList = new BusConsult()
        .baseMapper().wrapper()
        .eq(BusConsult::getIsDeleted, false)
        .list();
    }

}

io.Mapper 代码 初步判断定时任务执行的时候

public void addMapper(Class<?> type, Object mapper) {
    if (type != null && BaseMapper.class.isAssignableFrom(type)) {
      EntityClassFinder.find(type, null).ifPresent(clazz -> {
        if (mapper != null) {
          modelMapper.put(clazz, (BaseMapper<T, I>) mapper);
        }
      });
    }
  }

初始化未执行完 。

修改方案

/**
   * 获取实体类对应的 Mapper 接口
   *
   * @param modelClass 实体类
   * @return Mapper 接口
   */
 public M baseMapper(Class<T> modelClass) {
    if (modelMapper.containsKey(modelClass)) {
      return (M) modelMapper.get(modelClass);
    }

    this.sqlSessionTemplate.getConfiguration().getMapperRegistry().getMappers().forEach(mapper -> {
      addMapper(mapper, this.sqlSessionTemplate.getMapper(mapper));
    });

    if (modelMapper.containsKey(modelClass)) {
      return (M) modelMapper.get(modelClass);
    }

    throw new RuntimeException(modelClass.getName() + " Mapper interface not found");
  }