0

我已经用两个MySQL数据库配置了一个Micronaut应用程序,但它总是使用默认数据源执行操作。

如何使用多个数据库?

这是我的application.yml配置:

datasources:
  default:
      url: jdbc:mysql://localhost:3306/micronaut_demo
      username: root
      password: goti@181994
      dialect: MYSQL
  target:
      url: jdbc:mysql://localhost:3306/micronaut_demo_target
      username: root
      password: goti@181994
      dialect: MYSQL
jpa:
  default:
    packages-to-scan:
      - 'com.example'
    properties:
      hibernate:
        hbm2ddl:
          auto: create-drop
        show_sql: true
  target:
    properties:
      hibernate:
        hbm2ddl:
          auto: create-drop
        show_sql: true

这是我的Repository声明:

@Singleton
@Repository("target")
public class DepartmentRepositoryImpl implements  DepartmentRepository {
    private EntityManager entityManager;

    public DepartmentRepositoryImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    @ReadOnly
    public Optional<Department> findById(Long id) {
        return Optional.ofNullable(entityManager.find(Department.class, id));
    }

    @Override
    @Transactional
    public Department save(String name) {
        //save logic
    }
}

如您所见,我指定了要使用的数据源:

@Repository("target")
4

1 回答 1

0

您可以使用指定为依赖类型的注释来注释您的@Repositorybean,从而允许Microanut为每个创建的(以及每个在引擎盖下的)创建一个 bean:@EachBeanEntityManagerEntityManagerDataSource

@EachBean(EntityManager.class)
@Repository
public class DepartmentRepositoryImpl implements  DepartmentRepository {

    private EntityManager entityManager;

    public DepartmentRepositoryImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    @ReadOnly
    public Optional<Department> findById(Long id) {
        return Optional.ofNullable(entityManager.find(Department.class, id));
    }

    @Override
    @Transactional
    public Department save(String name) {
        //save logic
    }
}

然后,您可以DepartmentRepository根据所需的目标注入合格的DataSource

@Singleton
public class ServiceImpl implements Service {

    private DepartmentRepository departmentRepository;

    public ServiceImpl(@Named("target") DepartmentRepository departmentRepository) {
        this.departmentRepository = departmentRepository;
    }

    @Override
    public Department save(String name) {
        return this.departmentRepository.save(name);
    }
}

或动态使用注入ApplicationContext

@Singleton
public class ServiceImpl implements Service {

    private ApplicationContext applicationContext;

    public ServiceImpl(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Department save(String name) {
        return this.save(name, "default");
    }

    public Department save(String name, String targetDataSource) {
        return this.applicationContext.getBean(DepartmentRepository.class, Qualifiers.byName(target)).save(name);
    }
}
于 2021-04-13T01:09:39.427 回答