最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot Jpa多數(shù)據(jù)源(不同庫(kù))配置過(guò)程

 更新時(shí)間:2024年05月06日 09:38:05   作者:Mr-Wanter  
這篇文章主要介紹了springboot Jpa多數(shù)據(jù)源(不同庫(kù))配置過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

一、前言

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&currentSchema=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ù)庫(kù)方言
    @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ù)庫(kù)方言
        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就能用它來(lái)創(chuàng)建 EntityManager 了,然后 EntityManager 就可以針對(duì)數(shù)據(jù)庫(kù)執(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ù)庫(kù)方言
    @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ù)庫(kù)方言
        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就能用它來(lái)創(chuàng)建 EntityManager 了,然后 EntityManager 就可以針對(duì)數(shù)據(jù)庫(kù)執(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ī)開(kāi)發(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"_})_

三、遇到的問(wèn)題 數(shù)據(jù)庫(kù)連接報(bào)錯(cuò)

1.jdbcUrl is required with driverClassName

  • 主要原因是在1.0 配置數(shù)據(jù)源的過(guò)程中主要是寫(xiě)成: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&currentSchema=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沒(méi)有g(shù)etHibernateProperties

  • 與springboot版本有關(guān),上面代碼已修改。

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java的MyBatis框架中XML映射緩存的使用教程

    Java的MyBatis框架中XML映射緩存的使用教程

    MyBatis程序在做好XML映射后能夠有緩存的功能,這樣映射過(guò)SQL語(yǔ)句的配置以后就可以拿過(guò)來(lái)直接用了,這里我們來(lái)一起總結(jié)一下Java的MyBatis框架中XML映射緩存的使用教程
    2016-06-06
  • 詳解Java內(nèi)存溢出的幾種情況

    詳解Java內(nèi)存溢出的幾種情況

    這篇文章主要介紹了詳解Java內(nèi)存溢出的幾種情況,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • 解決Weblogic部署war找不到spring配置文件的問(wèn)題

    解決Weblogic部署war找不到spring配置文件的問(wèn)題

    這篇文章主要介紹了解決Weblogic部署war找不到spring配置文件的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。
    2021-07-07
  • Java基本數(shù)據(jù)類型包裝類原理解析

    Java基本數(shù)據(jù)類型包裝類原理解析

    這篇文章主要介紹了Java基本數(shù)據(jù)類型包裝類原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • 在MyBatis中使用<、<=?等特殊符號(hào)詳解

    在MyBatis中使用<、<=?等特殊符號(hào)詳解

    這篇文章主要介紹了在MyBatis中使用<、<=?等特殊符號(hào)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-04-04
  • Java實(shí)現(xiàn)UTF-8轉(zhuǎn)Unicode的代碼詳解

    Java實(shí)現(xiàn)UTF-8轉(zhuǎn)Unicode的代碼詳解

    在現(xiàn)代計(jì)算機(jī)處理中,字符編碼問(wèn)題始終是一個(gè)基礎(chǔ)而又重要的環(huán)節(jié),隨著國(guó)際化進(jìn)程不斷加快,UTF-8已成為互聯(lián)網(wǎng)傳輸中最常見(jiàn)的字符編碼之一,然而,在某些場(chǎng)景下需要將UTF-8編碼格式的字符串轉(zhuǎn)換為Unicode轉(zhuǎn)義序列,所以本文介紹了Java實(shí)現(xiàn)UTF-8轉(zhuǎn)Unicode的方法
    2025-06-06
  • Java結(jié)合EasyExcel構(gòu)建復(fù)雜多級(jí)表頭

    Java結(jié)合EasyExcel構(gòu)建復(fù)雜多級(jí)表頭

    在Java開(kāi)發(fā)中,處理Excel文件時(shí),構(gòu)建復(fù)雜的多級(jí)表頭是一項(xiàng)常見(jiàn)且具有挑戰(zhàn)性的任務(wù),下面小編就來(lái)和大家聊聊如何通過(guò)自定義方法實(shí)現(xiàn)多級(jí)表頭的構(gòu)建吧
    2025-03-03
  • Java實(shí)現(xiàn)飛機(jī)大戰(zhàn)-II游戲詳解

    Java實(shí)現(xiàn)飛機(jī)大戰(zhàn)-II游戲詳解

    《飛機(jī)大戰(zhàn)-II》是一款融合了街機(jī)、競(jìng)技等多種元素的經(jīng)典射擊手游。游戲是用java語(yǔ)言實(shí)現(xiàn),采用了swing技術(shù)進(jìn)行了界面化處理,感興趣的可以了解一下
    2022-02-02
  • 使用Java Servlet生成動(dòng)態(tài)二維碼的實(shí)現(xiàn)步驟

    使用Java Servlet生成動(dòng)態(tài)二維碼的實(shí)現(xiàn)步驟

    在現(xiàn)代互聯(lián)網(wǎng)時(shí)代,二維碼廣泛應(yīng)用于各個(gè)領(lǐng)域,包括支付、認(rèn)證、信息傳遞等,在Web開(kāi)發(fā)中,通過(guò)Java Servlet生成動(dòng)態(tài)二維碼是一個(gè)常見(jiàn)的需求,本文將介紹如何使用Java Servlet結(jié)合Google的ZXing庫(kù)生成動(dòng)態(tài)二維碼,需要的朋友可以參考下
    2023-11-11
  • Spring Boot + Vue 前后端分離開(kāi)發(fā)之前端網(wǎng)絡(luò)請(qǐng)求封裝與配置

    Spring Boot + Vue 前后端分離開(kāi)發(fā)之前端網(wǎng)絡(luò)請(qǐng)求封裝與配置

    這篇文章主要介紹了Spring Boot + Vue 前后端分離開(kāi)發(fā)之前端網(wǎng)絡(luò)請(qǐng)求封裝與配置方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下
    2019-05-05

最新評(píng)論

景泰县| 泽普县| 吴江市| 德兴市| 河东区| 二手房| 临泉县| 九江县| 聊城市| 辽中县| 龙山县| 泰安市| 宜都市| 荣成市| 黄石市| 吉水县| 繁昌县| 望奎县| 东丽区| 富民县| 长阳| 长海县| 博乐市| 阆中市| 永兴县| 阜新市| 视频| 崇左市| 赣榆县| 那曲县| 甘孜县| 将乐县| 东丽区| 柳江县| 辛集市| 公安县| 西安市| 襄城县| 台北县| 新巴尔虎左旗| 郓城县|