如何从辅助DataSource注入CrudRepository和EntityManager?

时间:2017-10-27 11:22:21

标签: java spring spring-data-jpa

我想在我的应用中初始化两个DataSource,如下所示:

@Configuration
public class DataSourceConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix="spring.datasource2")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

现在我想使用显式的辅助数据源,如下所示:

public class SecondaryDbService {
   @Autowired
   private EntityManager em;

   @Autowired
   private SecondaryCrudRepository dao;
}

interface SecondaryCrudRepository implements CrudRepository<SecondaryEntity, Long> {
}

如果按上述方式配置,该服务将使用数据源。

问题:如何告诉CrudRepository依赖“secondaryDataSource”?同样,我如何从“secondaryDataSource”中注入EntityManager

1 个答案:

答案 0 :(得分:1)

如果要使用多个数据源,关键是要在不同的包中为每个数据源配置。您需要根据应访问的数据源在这些包之间分离您的实体。

您还必须为这些包中的每个数据源实现实体和事务管理器。

多理论?在实际中它看起来像这样:

com.package1
- com.package1.entities
   - EntityClass1.java (annotated with @Entity)
- ConfigForDataSource1.java

com.package2
- com.package2.entities
   - EntityClass2.java (annotated with @Entity)
- ConfigForDataSource2.java

以下是ConfigForDataSource1的样子:

@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerDataSource1",
    basePackages = "com.package1",
    transactionManagerRef = "TransactionManagerDataSource1")
public class MasterDBConfig {

   @Bean(name="DataSource1")
   @ConfigurationProperties(prefix = "datasource1.datasource")
   public DataSource dataSource() {
       return DataSourceBuilder.create().build();
   }

   @Bean(name="entityManagerDataSource1")
   public LocalContainerEntityManagerFactoryBean entityManagerDataSource1(EntityManagerFactoryBuilder builder,@Qualifier("DataSource1") DataSource dataSource) {
       return builder.dataSource(dataSource).packages("com.package1").persistenceUnit("DataSource1").build();
    }

   @Bean(name = "TransactionManagerDataSource1")
   public PlatformTransactionManager TransactionManagerDataSource1(@Qualifier("entityManagerDataSource1") EntityManagerFactory entityManagerFactory) {
       return new JpaTransactionManager(entityManagerFactory);
   }
}

然后对包2做同样的事情并享受。

祝你好运!