您好,登錄后才能下訂單哦!
怎么在SpringBoot中實現(xiàn)多數(shù)據(jù)庫連接?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
主要使用兩個不同的數(shù)據(jù)庫,分別為:
mysql(springboot)【primary,優(yōu)先搜尋該數(shù)據(jù)庫】:mysql數(shù)據(jù)庫,包含User的信息
oracle(springboot): oracle數(shù)據(jù)庫, 包含Country信息
為了支持Mysql和Oracle數(shù)據(jù)庫,我們必須要在pom.xml文件中添加相應(yīng)的依賴。
<dependencies> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>javax.persistence-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies>
為了方便代碼的開發(fā),我們將mysql和oracle分開放在兩個不同的package下面,具體的包結(jié)構(gòu)如下:
將不同的模型分開放入mysql和oracle包目錄下,需要注意的是,mysql和oracle為兩個不同的數(shù)據(jù)庫,所以兩個數(shù)據(jù)庫中可能存在某個表名稱一致的場景。該場景下,會優(yōu)先匹配primary的數(shù)據(jù)庫,如果該數(shù)據(jù)庫down了,才會匹配另外一張表。所以,如果想要兩張表都正常使用,建議使用不同的Entity名稱。
我們在屬性文件application.properties中分別配置兩個單獨的jdbc連接,將所有關(guān)聯(lián)的Entity類和Repository映射到兩個不同的包中。
## jdbc-primary spring.datasource.url=jdbc:mysql://localhost:33306/springboot?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false spring.datasource.username=springboot spring.datasource.password=123456 spring.ds_mysql.driverClassName=com.mysql.jdbc.Driver ## jdbc-second spring.second.datasource.url=jdbc:oracle:thin:@localhost:1909/xxx.xxx.com spring.second.datasource.userName=springboot spring.second.datasource.password=123456 spring.second.datasource.driver-class-name=oracle.jdbc.OracleDriver ## jpa spring.jpa.hibernate.ddl-auto=none spring.jpa.show-sql=true spring.jpa.properties.hibernate.jdbc.time_zone=UTC spring.jpa.properties.hibernate.jdbc.fetch_size=500 spring.jpa.properties.hibernate.jdbc.batch_size=100
需要注意的是,在配置多個數(shù)據(jù)源期間,必須將其中一個數(shù)據(jù)源標(biāo)記為primary,否則Spring Boot會檢測到多個類型的數(shù)據(jù)源,從而無法正常啟動。
想要創(chuàng)建Data Source,我們必須先實例化org.springframework.boot.autoconfigure.jdbc.DataSourceProperties類,加載application.properties文件中配置的數(shù)據(jù)庫連接信息,并通過DataSourceProperties對象的初始化builder方法創(chuàng)建一個javax.sql.DataSource對象。
primary Data Source
@Primary @Bean(name = "mysqlDataSourceProperties") @ConfigurationProperties("spring.datasource") public DataSourceProperties dataSourceProperties() { return new DataSourceProperties(); } @Primary @Bean(name = "mysqlDataSource") @ConfigurationProperties("spring.datasource.configuration") public DataSource dataSource (@Qualifier("mysqlDataSourceProperties") DataSourceProperties mysqlDataSourceProperties) { return mysqlDataSourceProperties.initializeDataSourceBuilder() .type(HikariDataSource.class) .build(); }
Secondary Data Source
@Bean(name = "oracleDataSourceProperties") @ConfigurationProperties("spring.second.datasource") public DataSourceProperties dataSourceProperties() { return new DataSourceProperties(); } @Bean @ConfigurationProperties("spring.second.datasource.configuration") public DataSource oracleDataSource(@Qualifier("oracleDataSourceProperties") DataSourceProperties oracleDataSourceProperties) { return oracleDataSourceProperties.initializeDataSourceBuilder() .type(HikariDataSource.class) .build(); }
我們使用@Qualifier注解,自動關(guān)聯(lián)指定的DataSourceProperties.
定義實體類管理工廠的Bean
上面說了,應(yīng)用程序使用Spring Data JPA的repository接口將我們從實體管理器(Entity Manager)中抽象出來,從而進(jìn)行數(shù)據(jù)的訪問。這里,我們使用org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean這個Bean來創(chuàng)建EM實例,后面利用這個EM實例與JPA entities進(jìn)行交互。
由于我們這里有兩個數(shù)據(jù)源,所以我要為每個數(shù)據(jù)源單獨創(chuàng)建一個EntityManagerFactory。
Primary Entity Manager Factory
@Primary @Bean(name = "mysqlEntityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("mysqlDataSource") DataSource mysqlDataSource) { return builder.dataSource(mysqlDataSource) .packages("com.example.demo.model.mysql") .persistenceUnit("mysql") .build(); }
Secondary Entity Manager Factory
@Bean(name = "oracleEntityManagerFactory") public LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("oracleDataSource") DataSource oracleDataSource) { return builder.dataSource(oracleDataSource) .packages("com.example.demo.model.oracle") .persistenceUnit("oracle") .build(); }
我們使用@Qualifie注解,自動將DataSource關(guān)聯(lián)到對應(yīng)的EntityManangerFactory中。
在這里我們可以分別配置實體類管理工廠所管理的packages,為了方便開發(fā)和閱讀,分別將mysql和oracle關(guān)聯(lián)的實體類放在對應(yīng)的目錄下。
我們?yōu)槊總€數(shù)據(jù)庫創(chuàng)建一個JPA事務(wù)管理器。
查看源碼我們可以發(fā)現(xiàn)JPA事務(wù)管理器需要EntityManangerFactory作為入?yún)ⅲ岳蒙鲜龆x的EntityMangerFactory分別生成對應(yīng)的JPA事物管理器。
源碼:
public JpaTransactionManager(EntityManagerFactory emf) { this(); this.entityManagerFactory = emf; this.afterPropertiesSet(); }
Primary transaction manager
@Primary @Bean(name = "mysqlTransactionManager") public PlatformTransactionManager mysqlTransactionManager(final @Qualifier("mysqlEntityManagerFactory") LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory) { return new JpaTransactionManager(mysqlEntityManagerFactory.getObject()); }
Secondary transaction manager
@Bean(name = "oracleTransactionManager") public PlatformTransactionManager oracleTransactionManager( final @Qualifier("oracleEntityManagerFactory") LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory) { return new JpaTransactionManager(oracleEntityManagerFactory.getObject()); }
由于我們使用了兩個不同的數(shù)據(jù)源,所以我們必須使用@EnableJpaRepositories注解為每個數(shù)據(jù)源提供特定的信息。
進(jìn)入該注解源碼,我們可以發(fā)現(xiàn)默認(rèn)值如下:
/** * Annotation to enable JPA repositories. Will scan the package of the annotated configuration class for Spring Data * repositories by default. * * @author Oliver Gierke * @author Thomas Darimont */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(JpaRepositoriesRegistrar.class) public @interface EnableJpaRepositories { /** * Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) this * attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names. */ String[] basePackages() default {}; /** * Configures the name of the {@link EntityManagerFactory} bean definition to be used to create repositories * discovered through this annotation. Defaults to {@code entityManagerFactory}. * * @return */ String entityManagerFactoryRef() default "entityManagerFactory"; /** * Configures the name of the {@link PlatformTransactionManager} bean definition to be used to create repositories * discovered through this annotation. Defaults to {@code transactionManager}. * * @return */ String transactionManagerRef() default "transactionManager"; }
這里僅列了一些我們關(guān)心的方法。
從源碼我中我們可以看見,
basePackages: 使用此字段設(shè)置Repository的基本包,必須指向軟件包中repository所在目錄。
entityManagerFactoryRef:使用此字段引用默認(rèn)或自定義的Entity Manager Factory, 這里通過Bean的名稱進(jìn)行指定, 默認(rèn)Bean為entityManagerFactory。
transactionManagerRef:使用此字段引用默認(rèn)或自定義的事務(wù)管理器,這里通過Bean的名稱進(jìn)行指定,默認(rèn)Bean為transactionManager。
通過上面的內(nèi)容,我們?yōu)閮蓚€不同的數(shù)據(jù)源分別定義了不同的名稱,所以我們需要在這里分別將其注入容器中。
Primary
@Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = {"com.example.demo.repository.mysql"}, entityManagerFactoryRef = "mysqlEntityManagerFactory", transactionManagerRef = "mysqlTransactionManager") public class MysqlDataSourceConfiguration { ... }
secondary
@Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "com.example.demo.repository.oracle", entityManagerFactoryRef = "oracleEntityManagerFactory", transactionManagerRef = "oracleTransactionManager") public class OracleDataSourceConfiguration { ... }
完整的配置文件
primary
@Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = {"com.example.demo.repository.mysql"}, entityManagerFactoryRef = "mysqlEntityManagerFactory", transactionManagerRef = "mysqlTransactionManager") public class MysqlDataSourceConfiguration { @Primary @Bean(name = "mysqlDataSourceProperties") @ConfigurationProperties("spring.datasource") public DataSourceProperties dataSourceProperties() { return new DataSourceProperties(); } @Primary @Bean(name = "mysqlDataSource") @ConfigurationProperties("spring.datasource.configuration") public DataSource dataSource (@Qualifier("mysqlDataSourceProperties") DataSourceProperties mysqlDataSourceProperties) { return mysqlDataSourceProperties.initializeDataSourceBuilder() .type(HikariDataSource.class) .build(); } @Primary @Bean(name = "mysqlEntityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("mysqlDataSource") DataSource mysqlDataSource) { return builder.dataSource(mysqlDataSource) .packages("com.example.demo.model.mysql") .persistenceUnit("mysql") .build(); } @Primary @Bean(name = "mysqlTransactionManager") public PlatformTransactionManager transactionManager(final @Qualifier("mysqlEntityManagerFactory") LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory) { return new JpaTransactionManager(mysqlEntityManagerFactory.getObject()); } }
secondary
@Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "com.example.demo.repository.oracle", entityManagerFactoryRef = "oracleEntityManagerFactory", transactionManagerRef = "oracleTransactionManager") public class OracleDataSourceConfiguration { @Bean(name = "oracleDataSourceProperties") @ConfigurationProperties("spring.second.datasource") public DataSourceProperties dataSourceProperties() { return new DataSourceProperties(); } @Bean @ConfigurationProperties("spring.second.datasource.configuration") public DataSource oracleDataSource(@Qualifier("oracleDataSourceProperties") DataSourceProperties oracleDataSourceProperties) { return oracleDataSourceProperties.initializeDataSourceBuilder() .type(HikariDataSource.class) .build(); } @Bean(name = "oracleEntityManagerFactory") public LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("oracleDataSource") DataSource oracleDataSource) { return builder.dataSource(oracleDataSource) .packages("com.example.demo.model.oracle") .persistenceUnit("oracle") .build(); } @Bean public PlatformTransactionManager oracleTransactionManager( final @Qualifier("oracleEntityManagerFactory") LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory) { return new JpaTransactionManager(oracleEntityManagerFactory.getObject()); } }
關(guān)于怎么在SpringBoot中實現(xiàn)多數(shù)據(jù)庫連接問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。