您好,登錄后才能下訂單哦!
這篇文章主要介紹“SpringBoot+Jpa項目配置雙數據源怎么實現”,在日常操作中,相信很多人在SpringBoot+Jpa項目配置雙數據源怎么實現問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”SpringBoot+Jpa項目配置雙數據源怎么實現”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
server: port: 8080 spring: profiles: active: dev jackson: time-zone: GMT+8 # 這里是我們的數據庫配置地方 datasource: data1: #這里是數據庫一 driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://192.168.0.77:3306/test1?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&rewriteBatchedStatements=true username: root password: 123 type: com.alibaba.druid.pool.DruidDataSource data2: #這里是數據庫二 driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://192.168.0.88:3306/test2?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&rewriteBatchedStatements=true username: root password: 123 type: com.alibaba.druid.pool.DruidDataSource
當然到這里肯定是沒有結束的,需要配置一些參數,否則啟動會報錯
我們創建一個數據源的類,我們就給他取名為DataSourceConfig(這個名字自定義),在項目下創建一個包,方便管理
package com.eman.cdn.common.dataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; /** * @author https://blog.csdn.net/weixin_42782429?spm=1000.2115.3001.5343 * @date 2021/12/21 11:35 * <p> * description 數據源配置 */ @Configuration public class DataSourceConfig { # 這里是我們在yml文件配置的位置 private final static String DB_TEST1 = "spring.datasource.test1"; private final static String DB_TEST2= "spring.datasource.test1"; # 這個Bean名字子自定義只要不是重復的Bean名字就行了 @Bean(name = "test1Properties") @Qualifier("test1Properties") @Primary @ConfigurationProperties(DB_TEST1) public DataSourceProperties test1Properties() { return new DataSourceProperties(); } @Bean(name = "test1DataSource") @Qualifier("test1DataSource") @Primary @ConfigurationProperties(prefix = DB_TEST1) public DataSource test1DataSource() { return test1Properties().initializeDataSourceBuilder().build(); } @Bean(name = "test2Properties") @Qualifier("test2Properties") @ConfigurationProperties(DB_TEST2) public DataSourceProperties test2Properties() { return new DataSourceProperties(); } @Bean(name = "test2DataSource") @Qualifier("test2DataSource") @ConfigurationProperties(prefix = DB_ANALYSIS) public DataSource test2DataSource() { return test2Properties().initializeDataSourceBuilder().build(); } }
由于需要用到Mybaitis-plus所以你得先導入Mybaitis-Plus的依賴
<!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.0</version> </dependency>
package com.eman.xx.xxx.xx; import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties; import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.Objects; /** * @author tongJie * @date 2021/12/21 11:59 * <p> * description 日志處理端數據庫配置 */ @Configuration @EnableTransactionManagement @EnableJpaRepositories( // 配置連接工廠 entityManagerFactoryRef = "tes1Factory", // 配置事物管理器 transactionManagerRef = "tes1Transaction", // 設置Jpa 的 repository所在位置 basePackages = {"com.xx.xx.xx.**.repository"} ) // 設置掃描的mapper @MapperScan(basePackages ="xx.xx.xx.test1.**.mapper", sqlSessionTemplateRef = "tes1SqlSessionTemplate") public class AnalysisDataBaseConfig { @Autowired @Qualifier("tes1DataSource") private DataSource analysisDataSource; @Autowired private JpaProperties jpaProperties; @Autowired private HibernateProperties properties; // 以下是jpa的配置 /** * 連接工廠 * @param builder 創建工具 * @return 結果 */ @Bean(name = "tes1Factory") public LocalContainerEntityManagerFactoryBean tes1Factory(EntityManagerFactoryBuilder builder) { return builder // 設置數據源 .dataSource(analysisDataSource) //設置實體類所在位置.掃描所有帶有 @Entity 注解的類 .packages("xx.xx.xx.tes1.**.entity") // Spring會將EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后, // Repository就能用它來創建 EntityManager 了,然后 EntityManager 就可以針對數據庫執行操作 .persistenceUnit("tes1") // 為了加載yml中jpa下hibernate的相關配置 .properties(properties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings())) .build(); } /** * 配置事物管理器 * * @param builder 創建工具 * @return 結果 */ @Bean(name = "tes1Transaction") PlatformTransactionManager tes1Transaction(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(Objects.requireNonNull(analysisFactory(builder).getObject())); } // 以下是mybatis的配置 /** * 配置sqlSessionFactory * @return 結果 * @throws Exception 異常 */ @Bean("tes1SqlSessionFactory") public SqlSessionFactory tes1SqlSessionFactory() throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean(); sqlSessionFactory.setDataSource(analysisDataSource); sqlSessionFactory.setMapperLocations(new //這里填寫你mybaits的xml文件存放的路徑 PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/*.xml")); return sqlSessionFactory.getObject(); } /** * 配置sqlSessionTemplate * @return 結果 */ @Bean(name = "tes1SqlSessionTemplate") public SqlSessionTemplate tes1SqlSessionTemplate() throws Exception { return new SqlSessionTemplate(tes1SqlSessionFactory()); } }
以此類推之后每增加一個數據庫源就循環上面的方法
注意!!!!包一定要放對你配置的位置,否則不識別就會報錯!!!!!!
到此,關于“SpringBoot+Jpa項目配置雙數據源怎么實現”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。