我在 yml 中有多个数据库,如何获取特定国家/地区的存储库?我在运行时获取国家/地区名称,并且基于国家/地区名称,我需要对该国家/地区数据库进行操作,使用单个数据库从 yml 获取默认数据库存储库。
根据 micronaut 文档:在多数据源场景中,@io.micronaut.data.annotation.Repository 注释可用于指定要使用的数据源配置。默认情况下,Micronaut Data 将查找默认数据源。
我的查询对于所有数据库都保持不变,只有 db 实例在运行时被选中进行操作。
https://micronaut-projects.github.io/micronaut-data/snapshot/guide/index.html
错误:
Caused by: io.micronaut.context.exceptions.NonUniqueBeanException: Multiple possible bean candidates found: [io.micronaut.data.jdbc.operations.DefaultJdbcRepositoryOperations, io.micronaut.data.jdbc.operations.DefaultJdbcRepositoryOperations, io.micronaut.data.jdbc.operations.DefaultJdbcRepositoryOperations]
yml
datasources:
india-db:
validationQuery: SELECT 1 FROM DUAL
driverClass: oracle.jdbc.driver.OracleDriver
url: url-1
autoCommit: true
username: username
password: password
australia-db:
validationQuery: SELECT 1 FROM DUAL
driverClass: oracle.jdbc.driver.OracleDriver
url: url-2
autoCommit: true
username: password
password: password
japan-db:
validationQuery: SELECT 1 FROM DUAL
driverClass: oracle.jdbc.driver.OracleDriver
url: url-3
autoCommit: true
username: username
password: password
存储库
//@Repository(value = "india-db")
@JdbcRepository(dialect = Dialect.ORACLE)
public class AppRepository {
private final JdbcOperations jdbcOperations;
@Inject
public AppRepository(JdbcOperations jdbcOperations) {
this.jdbcOperations = jdbcOperations;
}
@Transactional
public String operation(){
}
}
服务
@Singleton
public class AppService {
AppRepository appRepository;
@Inject
public AppService(AppRepository appRepository){
this.appRepository=appRepository;
}
public void method(String country){
if(country.equals("india"){
//do india operation with india-db
appRepository.operation();
}else if(australia){
//do australia operation with australia -db
appRepository.operation();
}else if(japan){
//do japan operation with japan-db
appRepository.operation();
}
else{
throw exception();
}
}
}