본문 바로가기

programmer/SpringBoot

Spring Boot 다중 JPA ( mysql, postgresql 예제 )

1. build.gradle dependencies 설정

runtimeOnly('mysql:mysql-connector-java')
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.20'
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.2.2.Final'

2. application.properties 설정

<필수! 주의>
DB 한 개 사용한다면 url 만 적으면 되지만 2개 이상인 경우 꼭 jdbc- 를 입력해 준다.
**주의 spring.~~~ <- 문자에  대문자, 특수문자 '-','_' 사용 안됨

# JDBC Connection url for the database
spring.datasource.jdbc-url=jdbc:mysql://IP:PORT/DBNAME?useUnicode=true&charaterEncoding=utf-8&serverTimezone=Asia/Seoul
spring.datasource.username=ID
spring.datasource.password=PASS
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#PostgreSQL Connection url for the database
spring.connpgsqltest.driverClassName=org.postgresql.Driver
spring.connpgsqltest.jdbc-url=jdbc:postgresql://IP:PORT/DBNAME?charSet=utf-8&prepareThreshold=1
spring.connpgsqltest.username=ID
spring.connpgsqltest.password=PASS

3. Config 추가

config package에 각 JPA 별 config를 생성한다.

<필수! 주의>
각 JPA 별로 repository, entity를 구분해서 사용하므로 각 DB 별 패키지 분리를 하는게 좋다.
com.hmns.data.repositorypostgre ="" --> @Repository 어노테이션이 있는 interface package 명을 입력getDataSource()).packages("") --> @Entity 어노테이션이 있는 interface package 명을 입력
@Primary 어노테이션은 적용하려는 DB 중 한 곳에만 꼭 선언해줘야 하니 잊지말고 원하는 메인 DB @Bean에 선언해 준다.

3.1 mysql DB config

package com.~~~.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;

@Configuration
@EnableJpaRepositories
        (
                basePackages = "com.~~~.repository.mysql",
                entityManagerFactoryRef = "mysqlFactoryBean",
                transactionManagerRef = "mysqlTransactionManager"
        )
public class JdbcMysqlConfig
{
    @Primary
    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDataSource()
    {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "mysqlFactoryBean")
    public LocalContainerEntityManagerFactoryBean getFactoryBean(EntityManagerFactoryBuilder builder)
    {
        return builder.dataSource(getDataSource()).packages("com.~~~.model.mysql").build();
    }
    @Primary
    @Bean(name = "mysqlTransactionManager")
    PlatformTransactionManager getTransactionManager(EntityManagerFactoryBuilder builder)
    {
        return new JpaTransactionManager(getFactoryBean(builder).getObject());
    }
}

3.2 postgre DB config

package com.~~~.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;

@Configuration
@EnableJpaRepositories
        (
                basePackages = "com.~~~.repository.postgre",
                entityManagerFactoryRef = "pgsqlFactoryBean",
                transactionManagerRef = "pgsqlTransactionManager"
        )
public class JdbcPgsqlConfig
{
//    @Primary
    @Bean(name = "pgsqlDataSource")
    @ConfigurationProperties(prefix = "spring.connpgsqltest")
    public DataSource getDataSource()
    {
        return DataSourceBuilder.create().build();
    }

//    @Primary
    @Bean(name = "pgsqlFactoryBean")
    public LocalContainerEntityManagerFactoryBean getFactoryBean(EntityManagerFactoryBuilder builder)
    {
        return builder.dataSource(getDataSource()).packages("com.~~~.model.postgre").build();
    }

//    @Primary
    @Bean(name = "pgsqlTransactionManager")
    PlatformTransactionManager getTransactionManager(EntityManagerFactoryBuilder builder)
    {
        return new JpaTransactionManager(getFactoryBean(builder).getObject());
    }
}

 

반응형
사업자 정보 표시
라울앤알바 | 장수호 | 서울특별시 관악구 봉천로 13나길 58-10, 404호(봉천동) | 사업자 등록번호 : 363-72-00290 | TEL : 010-5790-0933 | Mail : shjang@raulnalba.com | 통신판매신고번호 : 2020-서울관악-0892호 | 사이버몰의 이용약관 바로가기