본문 바로가기
개발/java,spring,springboot

Spring boot jpa datasource 여러 개 설정(multiple datasource)

by 개발자종혁 2021. 4. 7.
728x90

설정

mysql build하기

docker로 mysql build 하기 (tistory.com)

 

docker로 mysql build 하기

도커 다운로드 도커다운로드 도커 build Dockerfile FROM mysql:8.0.21 # 인코딩 ENV LC_ALL=C.UTF-8 ENV character-set-server utf8 ENV collation-server utf8_general_ci ENV default-character-set utf8 ENV d..

jonghyeok-dev.tistory.com

  • 추가로 build 하나 더(secondary container)
    docker run -i -d -p 3308:3306 --name mysql_container2 mysql_image mysqld --character-set-server=utf8 --collation-server=utf8_general_ci

 

 

 

 

build.gradle

plugins {
    id 'org.springframework.boot' version '2.3.9.RELEASE'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id "com.ewerk.gradle.plugins.querydsl" version "1.0.10"

    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '8'

repositories {
    mavenCentral()
}

dependencies {

    // web
    implementation 'org.springframework.boot:spring-boot-starter-web'

    // jpa
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'


    runtimeOnly 'mysql:mysql-connector-java'

    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

application.yaml

server:
  port: 9090

spring:

  jpa:
    hibernate:
        ddl-auto: create  # create or update
        use-new-id-generator-mappings: false
        naming:
            physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    properties:
      hibernate.dialect: org.hibernate.dialect.MySQL5InnoDBDialect

primary:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3307/SCHEMA_NAME?serverTimezone=UTC&characterEncoding=UTF-8
        username: root
        password: password

secondary:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3308/SCHEMA_NAME?serverTimezone=UTC&characterEncoding=UTF-8
    username: root
    password: password

PrimaryDataSourceConfig.java

package com.example.demo.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import com.zaxxer.hikari.HikariDataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "primaryEntityManagerFactory",
        transactionManagerRef = "primaryTransactionManager",
        basePackages = { "com.example.demo.primary.repository" }
)
public class PrimaryDataSourceConfig {

    @Primary
    @Bean
    @ConfigurationProperties("primary.datasource")
    public DataSourceProperties primaryDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Primary
    @Bean
    @ConfigurationProperties("primary.datasource.configuration")
    public DataSource primaryDataSource(@Qualifier("primaryDataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(EntityManagerFactoryBuilder builder,
                                                                           @Qualifier("primaryDataSource") DataSource dataSource) {
        return builder
                        .dataSource(dataSource)
                        .packages("com.example.demo.primary.model")
                        .persistenceUnit("primaryEntityManager")
                        .build();
    }

    @Primary
    @Bean
    public PlatformTransactionManager primaryTransactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

SecondaryDataSourceConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "secondaryEntityManagerFactory",
        transactionManagerRef = "secondaryTransactionManager",
        basePackages = { "com.example.demo.secondary.repository" }
)
public class SecondaryDataSourceConfig {

    @Bean
    @ConfigurationProperties("secondary.datasource")
    public DataSourceProperties secondaryDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.configuration")
    public DataSource secondaryDataSource(@Qualifier("secondaryDataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(EntityManagerFactoryBuilder builder,
                                                                           @Qualifier("secondaryDataSource") DataSource dataSource) {
        return builder
                        .dataSource(dataSource)
                        .packages("com.example.demo.secondary.model")
                        .persistenceUnit("secondaryEntityManager")
                        .build();
    }

    @Bean
    public PlatformTransactionManager secondaryTransactionManager(@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

 

 

전체 코드

 

jonghyeok34/spring-jpa-multiple-datasource (github.com)

 

jonghyeok34/spring-jpa-multiple-datasource

Contribute to jonghyeok34/spring-jpa-multiple-datasource development by creating an account on GitHub.

github.com

 

728x90

댓글