본문 바로가기
📚 개발 공부

[JPA] 다중 데이터베이스 구성설정

by cheonvi 2023. 1. 25.

멀티 데이터베이스를 사용 할 경우 JPA에서는 DB를 구성을 해야 합니다. 이번 글에서는 다중 데이터베이스를 설정하는 방법에 대해서 설명하겠습니다. 

SpringBoot에서는 다중 데이터베이스를 자동으로 구성을 하지 못합니다. 따라서 수동으로 구성설정을 해줘야 합니다. 

수동으로 구성설정이 아래와같이 항목에 대해서 설정을 해야합니다. 

 

1. 리소스 설정

2. db 정보 생성

3. Hibernate설정

4. TransactionManager 설정

 

 

■ DB Configuration

. 다중 DB를 설정할때, @Primary 어노테이션을 이용하여 Master가 되는 데이터베이스를 지정해야 합니다. 

 

▶ Master 데이터베이스 구성

/**
 * 
 */
/**
 * @author cheonvi
 *
 */
package com.xxx.xxxx.config;

import java.util.HashMap;

import javax.sql.DataSource;

import org.hibernate.cfg.AvailableSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories(
		
		 basePackages = { "com.xxx.xxx.stats","com.xxx.xxx.data" }, 
		    entityManagerFactoryRef = "xxxEntityManager", 
		    transactionManagerRef = "xxxTransactionManager"
		)
public class PersistencxxxConfiguration {
	
	@Autowired
    private Environment env;
    
    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean xxxEntityManager() {
        LocalContainerEntityManagerFactoryBean em
          = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(xxxDataSource());
        em.setPackagesToScan(
          new String[] { "com.xxx.xxx.stats","com.xxx.xxx.data" });

        HibernateJpaVendorAdapter vendorAdapter
          = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put(AvailableSettings.HBM2DDL_AUTO, env.getProperty("datasource.xxx.hibernate.ddl-auto"));
        properties.put(AvailableSettings.SHOW_SQL, env.getProperty("datasource.xxx.hibernate.show_sql"));
        properties.put(AvailableSettings.FORMAT_SQL, env.getProperty("datasource.xxx.hibernate.format_sql"));
        properties.put(AvailableSettings.DIALECT, env.getProperty("datasource.xxx.hibernate.dialect"));
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean
    public DataSource xxxDataSource() {
 
        DriverManagerDataSource dataSource
          = new DriverManagerDataSource();
        dataSource.setDriverClassName(
          env.getProperty("datasource.xxx.driver-class-name"));
        dataSource.setUrl(env.getProperty("datasource.xxx.url"));
        dataSource.setUsername(env.getProperty("datasource.xxx.username"));
        dataSource.setPassword(env.getProperty("datasource.xxx.password"));

        return dataSource;
    }

    @Primary
    @Bean
    public PlatformTransactionManager xxxTransactionManager() {
 
        JpaTransactionManager transactionManager
          = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
        		xxxEntityManager().getObject());
        return transactionManager;
    }
	
}

 

 

▶ Second 데이터베이스 구성

 

/**
 * 
 */
/**
 * @author cheonvi
 *
 */
package com.xxx.xxx.config;

import java.util.HashMap;

import javax.sql.DataSource;

import org.hibernate.cfg.AvailableSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories(
		
		 basePackages = { "com.xxx.xxx.quota","com.xxx.xxx.policy","com.xxx.xxx.project" }, 
		    entityManagerFactoryRef = "adminEntityManager", 
		    transactionManagerRef = "adminTransactionManager"
		)
public class PersistencxxxxConfiguration {
	
	
	@Autowired
    private Environment env;
    
    @Bean
    public LocalContainerEntityManagerFactoryBean xxxxEntityManager() {
        LocalContainerEntityManagerFactoryBean em
          = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(adminDataSource());
        em.setPackagesToScan(
          new String[] { "com.xxx.xxx.quota","com.xxx.xxx.policy","com.xxx.xxx.project" });

        HibernateJpaVendorAdapter vendorAdapter
          = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put(AvailableSettings.HBM2DDL_AUTO, env.getProperty("datasource.xxxx.hibernate.ddl-auto"));
        properties.put(AvailableSettings.SHOW_SQL, env.getProperty("datasource.xxxx.hibernate.show_sql"));
        properties.put(AvailableSettings.FORMAT_SQL, env.getProperty("datasource.xxxx.hibernate.format_sql"));
        properties.put(AvailableSettings.DIALECT, env.getProperty("datasource.xxxx.hibernate.dialect"));
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Bean
    public DataSource xxxxDataSource() {
 
        DriverManagerDataSource dataSource
          = new DriverManagerDataSource();
        dataSource.setDriverClassName(
          env.getProperty("datasource.xxxx.driver-class-name"));
        dataSource.setUrl(env.getProperty("datasource.xxxx.url"));
        dataSource.setUsername(env.getProperty("datasource.xxxx.username"));
        dataSource.setPassword(env.getProperty("datasource.xxxx.password"));

        return dataSource;
    }

    @Bean
    public PlatformTransactionManager xxxxTransactionManager() {
 
        JpaTransactionManager transactionManager
          = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
        		xxxxEntityManager().getObject());
        return transactionManager;
    }
	
}

 

jpa repository가 여러개 있을 경우 

basePackages = { "com.xxx.xxx.quota","com.xxx.xxx.policy","com.xxx.xxx.project" } 으로 설정 할 수 있습니다.

 

 

출처 및 참고 사이트

 

https://www.baeldung.com/spring-data-jpa-multiple-databases

 

Spring JPA – Multiple Databases | Baeldung

How to set up Spring Data JPA to work with multiple, separate databases.

www.baeldung.com