1.我们需要在application.yml中配置第多个连接
结构:
spring:
profiles:local
datasource:
aDataSource:
type:xx
url:xx
username:xx
....
bDataSource:
type:xx
url:xx
username:xx
....
2.我们需要创建一个DataSourceConfig,将上面多个数据源进行注册
@Configuration public class DataSourceConfig { @Bean(name = "aDataSource") @Qualifier("aDataSource") @Primary @ConfigurationProperties(prefix="spring.datasource.aDataSource") public DataSource wdxhDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "bDataSource") @Qualifier("bDataSource") @ConfigurationProperties(prefix="spring.datasource.bDataSource") public DataSource fileUploadDataSource() { return DataSourceBuilder.create().build(); } }
@Primary,加此注解标注为主从关系;
@Qualifier,加上此注册则表示根据id去声名或者扫描某个组件,如两个数据源中的表名相同则需要预先把两个组名的名字区分开来,
如:@Repository("a_user_repository"),然后通过上面的注释@Autowaried @Qualifier("a_user_repository")来精确的找到组件id进行注入,否则会报组件未定义的错误;
3.我们需要定义多个DatabaseConfig来配置所对应的扫描路径,如repository路径entity路径等。
@Configuration @EnableJpaRepositories(entityManagerFactoryRef="entityManagerFactoryA", transactionManagerRef = "transactionManagerA", basePackages = {"com.test.persistence.A.repository"}) @EnableTransactionManagement public class FileUploadDatabaseConfiguration { @Autowired @Qualifier("aDataSource") private DataSource aDataSource; @Autowired private JpaProperties jpaProperties; @Bean
@Primary
public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); adapter.setDatabase(Database.MYSQL); adapter.setShowSql(false); adapter.setGenerateDdl(true); adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect"); return adapter; } @Bean(name = "entityManagerFactoryA")@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) { return builder .dataSource(aDataSource) .properties(getVendorProperties(aDataSource)) .packages("com.test.persistence.A.entity") //设置实体类所在位置 .persistenceUnit("aPersistenceUnit") .build(); } private Map<String, String> getVendorProperties(DataSource dataSource) { return jpaProperties.getHibernateProperties(dataSource); } @Bean(name = "transactionManagerA") @Primary public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { JpaTransactionManager manager = new JpaTransactionManager(); manager.setEntityManagerFactory(entityManagerFactory); return manager; } @Bean public BeanPostProcessor persistenceTranslation() { return new PersistenceAnnotationBeanPostProcessor(); }
类似的,新增DatabaseConfig,其结构一样就可以了,区别是DataSource是需要对应的,无@Primary注解。
3.调用对应的repository进行表操作,这里跟平时注入没什么两样
@Autowired
private RepostoryA repostoryA;
@Autowired
private RepostoryB repostoryB;