springboot Jpa多數(shù)據(jù)源(不同庫)配置過程
一、前言
springboot版本不同對(duì)多數(shù)據(jù)源配置代碼有一定影響,部分方法和配置略有不同。
本文采用的springboot版本為2.3.12,數(shù)據(jù)源為mysql和postgresql
二、配置實(shí)戰(zhàn)
2.1 基礎(chǔ)pom
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies>
2.2 配置文件
spring.datasource.mysql.jdbc-url=jdbc:mysql://localhost:3306/heilongjiang?characterEncoding=UTF-8&useSSL=false&useTimezone=true&serverTimezone=GMT%2B8 spring.datasource.mysql.driver-class-name=com.mysql.jdbc.Driver spring.datasource.mysql.username=root spring.datasource.mysql.password=123456 spring.datasource.pg.jdbc-url=jdbc:postgresql://localhost:5432/hljsyjt?useUnicode=true&characterEncoding=utf8¤tSchema=emergencydev,expert,public spring.datasource.pg.driver-class-name=org.postgresql.Driver spring.datasource.pg.username=postgres spring.datasource.pg.password=postgres spring.jpa.properties.hibernate.mysql-dialect=org.hibernate.dialect.MySQLDialect spring.jpa.properties.hibernate.pg-dialect=org.hibernate.dialect.PostgreSQLDialect spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
2.3 數(shù)據(jù)源配置類
package com.gsafety.bg.industrial.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; /** * @author Mr.wanter * @time 2021-8-11 0011 * @description */ @Configuration public class DataSourceConfig { @Bean("dataSourceMysql") @Primary @ConfigurationProperties(prefix = "spring.datasource.mysql") public DataSource dataSourceMysql() { return DataSourceBuilder.create().build(); } @Bean("dataSourcePg") @ConfigurationProperties(prefix = "spring.datasource.pg") public DataSource dataSourcePg() { return DataSourceBuilder.create().build(); } }
2.4 數(shù)據(jù)源指定配置類
mysql指定數(shù)據(jù)源:
package com.gsafety.bg.industrial.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; 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.context.annotation.Primary; 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.HashMap; import java.util.Map; /** * @author Mr.wanter * @time 2021-8-11 0011 * @description */ @Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactoryMysql",//配置連接工廠 entityManagerFactory transactionManagerRef = "transactionManagerMysql", //配置 事物管理器 transactionManager basePackages = {"com.gsafety.bg.industrial.dao"}//設(shè)置持久層所在位置 ) public class MysqlDataSourceConfig { @Autowired private JpaProperties jpaProperties; @Autowired private HibernateProperties hibernateProperties; // 自動(dòng)注入配置好的數(shù)據(jù)源 @Autowired @Qualifier("dataSourceMysql") private DataSource mysqlDataSource; // 獲取對(duì)應(yīng)的數(shù)據(jù)庫方言 @Value("${spring.jpa.properties.hibernate.mysql-dialect}") private String mysqlDialect; /** * @param builder * @return */ @Bean(name = "entityManagerFactoryMysql") @Primary public LocalContainerEntityManagerFactoryBean entityManagerFactoryMysql(EntityManagerFactoryBuilder builder) { Map<String, String> map = new HashMap<>(); // 設(shè)置對(duì)應(yīng)的數(shù)據(jù)庫方言 map.put("hibernate.dialect", mysqlDialect); jpaProperties.setProperties(map); Map<String, Object> properties = hibernateProperties.determineHibernateProperties( jpaProperties.getProperties(), new HibernateSettings()); return builder //設(shè)置數(shù)據(jù)源 .dataSource(mysqlDataSource) //設(shè)置數(shù)據(jù)源屬性 .properties(properties) //設(shè)置實(shí)體類所在位置.掃描所有帶有 @Entity 注解的類 .packages("com.gsafety.bg.industrial.dao.po") // Spring會(huì)將EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后, // Repository就能用它來創(chuàng)建 EntityManager 了,然后 EntityManager 就可以針對(duì)數(shù)據(jù)庫執(zhí)行操作 .persistenceUnit("mysqlPersistenceUnit") .build(); } /** * 配置事物管理器 * * @param builder * @return */ @Bean(name = "transactionManagerMysql") @Primary PlatformTransactionManager transactionManagerMysql(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactoryMysql(builder).getObject()); } }
pg指定數(shù)據(jù)源:
package com.gsafety.bg.industrial.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; 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.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.HashMap; import java.util.Map; /** * @author Mr.wanter * @time 2021-8-11 0011 * @description */ @Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactoryPg",//配置連接工廠 entityManagerFactory transactionManagerRef = "transactionManagerPg", //配置 事物管理器 transactionManager basePackages = {"com.gsafety.bg.data.dao"}//設(shè)置持久層所在位置 ) public class PgDataSourceConfig { @Autowired private JpaProperties jpaProperties; @Autowired private HibernateProperties hibernateProperties; //自動(dòng)注入配置好的數(shù)據(jù)源 @Autowired @Qualifier("dataSourcePg") private DataSource PgDataSource; // 獲取對(duì)應(yīng)的數(shù)據(jù)庫方言 @Value("${spring.jpa.properties.hibernate.pg-dialect}") private String pgDialect; /** * @param builder * @return */ @Bean(name = "entityManagerFactoryPg") public LocalContainerEntityManagerFactoryBean entityManagerFactoryPg(EntityManagerFactoryBuilder builder) { Map<String, String> map = new HashMap<>(); // 設(shè)置對(duì)應(yīng)的數(shù)據(jù)庫方言 map.put("hibernate.dialect", pgDialect); jpaProperties.setProperties(map); Map<String, Object> properties = hibernateProperties.determineHibernateProperties( jpaProperties.getProperties(), new HibernateSettings()); return builder //設(shè)置數(shù)據(jù)源 .dataSource(PgDataSource) //設(shè)置數(shù)據(jù)源屬性 .properties(properties) //設(shè)置實(shí)體類所在位置.掃描所有帶有 @Entity 注解的類 .packages("com.gsafety.bg.data.dao.po") // Spring會(huì)將EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后, // Repository就能用它來創(chuàng)建 EntityManager 了,然后 EntityManager 就可以針對(duì)數(shù)據(jù)庫執(zhí)行操作 .persistenceUnit("pgPersistenceUnit") .build(); } /** * 配置事物管理器 * * @param builder * @return */ @Bean(name = "transactionManagerPg") PlatformTransactionManager transactionManagerPg(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactoryPg(builder).getObject()); } }
2.5 如何應(yīng)用
數(shù)據(jù)源配置類中指定了掃描po和dao包的路徑
例如entityManagerFactoryPg中的com.gsafety.bg.data.dao.po和com.gsafety.bg.data.dao
那么我們只需要在指定的包下創(chuàng)建po和dao即可,service包層次不受影響,自定義即可。
三數(shù)據(jù)源同理即可。
左側(cè)為雙數(shù)據(jù)源(與本篇實(shí)戰(zhàn)內(nèi)容一致),右側(cè)為三數(shù)據(jù)源(三數(shù)據(jù)源目錄結(jié)構(gòu)示例)。
其他編碼常規(guī)開發(fā)即可
- po:
@Entity @Builder @Data @AllArgsConstructor @NoArgsConstructor @Table(name = "jc_repertory") public class JcRepertoryPO implements Serializable { //some fields }
- dao:
public interface JcRepertoryDao extends JpaRepository<JcRepertoryPO, String>, JpaSpecificationExecutor<JcRepertoryPO> { }
- service:
public interface JcRepertoryService { List<JcRepertoryPO> list(); }
@Service public class JcRepertoryServiceImpl implements JcRepertoryService { @Resource private JcRepertoryDao jcRepertoryDao; @Override public List<JcRepertoryPO> list() { List<JcRepertoryPO> all = jcRepertoryDao.findAll(); return all; } }
- controller 略
啟動(dòng)類添加掃描
@SpringBootApplication_(_scanBasePackages = _{_"com.gsafety.bg.data", "com.gsafety.bg.industrial"_})_
三、遇到的問題 數(shù)據(jù)庫連接報(bào)錯(cuò)
1.jdbcUrl is required with driverClassName
- 主要原因是在1.0 配置數(shù)據(jù)源的過程中主要是寫成:spring.datasource.url 和spring.datasource.driverClassName。
- 而在2.0升級(jí)之后需要變更成:spring.datasource.jdbc-url和spring.datasource.driver-class-name
spring.datasource.pg.jdbc-url=jdbc:postgresql://localhost:5432/hljsyjt?useUnicode=true&characterEncoding=utf8¤tSchema=emergencydev,expert,public spring.datasource.pg.driver-class-name=org.postgresql.Driver
2.Paging query needs to have a Pageable parameter!
- 原系統(tǒng)中對(duì)jap的Repository進(jìn)行了封裝,采用常規(guī)方式調(diào)用即可。
3.more than one ‘primary’ bean found among candidates
- 2.4 數(shù)據(jù)源指定配置類 中只有一個(gè)類中的方法添加 @Primary 另外一個(gè)不要加這個(gè)注解
4.互聯(lián)網(wǎng)查詢的代碼中JpaProperties沒有g(shù)etHibernateProperties
- 與springboot版本有關(guān),上面代碼已修改。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java反編譯工具jd-gui-osx?for?mac?M1芯片無法使用的問題及解決
這篇文章主要介紹了java反編譯工具jd-gui-osx?for?mac?M1芯片無法使用的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01idea環(huán)境下Maven無法正常下載pom中配置的包問題
這篇文章主要介紹了idea環(huán)境下Maven無法正常下載pom中配置的包的問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06IntelliJ IDEA下Maven創(chuàng)建Scala項(xiàng)目的方法步驟
這篇文章主要介紹了IntelliJ IDEA下Maven創(chuàng)建Scala項(xiàng)目的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06JAVA下單接口優(yōu)化實(shí)戰(zhàn)TPS性能提高10倍
今天小編就為大家分享一篇關(guān)于JAVA下單接口優(yōu)化實(shí)戰(zhàn)TPS性能提高10倍,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-12-12關(guān)于Java項(xiàng)目讀取resources資源文件路徑的那點(diǎn)事
這篇文章主要介紹了關(guān)于Java項(xiàng)目讀取resources資源文件路徑的那點(diǎn)事,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07Springboot錯(cuò)誤頁面和錯(cuò)誤信息定制操作
這篇文章主要介紹了Springboot錯(cuò)誤頁面和錯(cuò)誤信息定制操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10