헤르메스 LIFE

[Spring Boot] HikariCP를 이용한 Multi Database Connection + JPA 본문

Spring Boot Framework

[Spring Boot] HikariCP를 이용한 Multi Database Connection + JPA

헤르메스의날개 2022. 2. 24. 23:38
728x90

springboot.zip
0.14MB

개발환경

1. STS 버전 : 4.13.1

2. JDK 버전 : OpenJDK 11.0.14_9_x64

3. Tomcat 버전 : 9.0.56

4. Maven 버전 : 3.8.4

5. Spring 버전 : Spring Boot 2.6.3

6. Database : Docker 에 DB 설치

- primary - PostgreSQL 13.3
- secondary - MySQL DB 8.0.28

8. lombok


PostgreSQL 연결하기 - Docker 를 이용한 PostgreSQL 설치

https://hermeslog.tistory.com/541

 

[SpringBoot] PostgreSQL 연결하기

IDE : IntelliJ JDK : OpenJDK 11 Framework : Spring Boot 2.5.2 Database : PostgreSQL 최신버전 ( 라이센스도 소스공개의무도 없음 ) 첨부파일이 MySqlRunner 로 되어있는데.. MySQL 접속테스트 중 소스만 바..

hermeslog.tistory.com

MySQL 연결하기 - Docker 를 이용한 MySQL 설치

https://hermeslog.tistory.com/540

 

[SpringBoot] MySQL/Maria 연결하기

IDE : IntelliJ JDK : OpenJDK 11 Framework : Spring Boot 2.5.2 Database : MySql 최신버전 ( Oracle 에 라이센스비를 지급해야 하고, 소스공개의 의무가 존재함 ) Maria 최신버전 ( 소스공개의 의무가 존재함..

hermeslog.tistory.com

 

 

PostgreSQL 접속하기 - Docker 를 이용한 PostgreSQL 연결

# Docker에 설치된 컨테이너 목록 조회
> docker ps -a

# Docker 컨테이너 실행
> docker exec -it postgres_boot bash

# postgres 사용자 접속
> su - postgres

# postgres 계정접속
> psql --username hermeswing --dbname springboot

# 테이블 목록 조회
> \dt
          List of relations
 Schema |  Name  | Type  |   Owner
--------+--------+-------+------------
 public | mybook | table | hermeswing
 public | test   | table | hermeswing

 


1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.study</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>springboot</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mustache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2. application.xml

server:
  port: 9090
  servlet:
    context-path: /
    encoding:
      charset: UTF-8
      enabled: true
      force: true


### Prime Database Details
app:
  datasource:
    primary:
      url: jdbc:postgresql://localhost:5432/springboot
      username: hermeswing
      password: pass
      hikari:
        idle-timeout: 10000
        maximum-pool-size: 10
        minimum-idle: 5
        pool-name: PrimeHikariPool

    product:
      url: jdbc:mysql://localhost:3306/springboot?allowPublicKeyRetrieval=true
      username: hermeswing
      password: pass
      hikari:
        idle-timeout: 10000
        maximum-pool-size: 10
        minimum-idle: 5
        pool-name: PrimeHikariPool
      
spring:
  h2:
    console:
      enabled: true
      path: /h2-console
      
  jpa:
    generate-ddl: true
    hibernate:
      ddl-auto: create
    show-sql: false
    properties:
      hibernatte:
        format_sql: true
  profiles:
    active: local


logging:
  level:
    org:
      hibernate:
        SQL: debug
        type:
          descriptor:
            SQL: trace

PrimaryDatasourceConfig.java

Default DB 지정은 @Primary 를 지정해주면 됩니다.

package com.study.springboot.config;

import java.util.HashMap;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableJpaRepositories(basePackages = { "com.study.springboot.system" },    // Repository 경로
        entityManagerFactoryRef = "primeEntityManager", transactionManagerRef = "primeTransactionManager")
public class PrimaryDatasourceConfig {
    @Autowired
    Environment env;

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "app.datasource.primary")     // prefix 설정
    public DataSourceProperties primeDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    public DataSource primeDataSource() {
        return primeDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean primeEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(primeDataSource());
        
        // Entiry Package 경로
        em.setPackagesToScan(new String[] { "com.study.springboot.system.entity" });
        em.setPersistenceUnitName("primeEntityManager");                               // 영속성 객체 이름을 지정
        
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        
        // Hibernate 설정
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));

        em.setJpaPropertyMap(properties);

        return em;
    }

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

}

SecondaryDatasourceConfiguration.java

package com.study.springboot.config;

import java.util.HashMap;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableJpaRepositories(basePackages = { "com.study.springboot.product" },     // Repository 경로
        entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
public class SecondaryDatasourceConfiguration {
    @Autowired
    Environment env;

    @Bean
    @ConfigurationProperties(prefix = "app.datasource.product")     // prefix 설정
    public DataSourceProperties productDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DataSource productDataSource() {
        return productDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean productEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(productDataSource());

        // Entiry Package 경로
        em.setPackagesToScan(new String[] { "com.study.springboot.product.entity" });

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        // Hibernate 설정
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));

        em.setJpaPropertyMap(properties);

        return em;
    }

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

}

ProductRepository.java

package com.study.springboot.product.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.study.springboot.product.entity.Product;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}

MemberRepository.java

package com.study.springboot.system.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.study.springboot.system.entity.Member;

@Repository
public interface MemberRepository extends CrudRepository<Member, Long> {
}

MemberRepositoryTest.java

package com.study.springboot.system.repository;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import com.study.springboot.product.entity.Product;
import com.study.springboot.product.repository.ProductRepository;
import com.study.springboot.system.entity.Member;

@RunWith(SpringRunner.class)
@DataJpaTest
// @SpringTest
public class MemberRepositoryTest {

    @Autowired(required = true)
    MemberRepository memberRepository;

    @Autowired(required = true)
    ProductRepository productRepository;

    @Test
    // @Transactional // Default primary 를 Call 합니다.
    public void testMember() throws Exception {
        // Given
        Member memberA = new Member("memberA", "");

        // When
        Member member     = memberRepository.save(memberA);
        Member findMember = memberRepository.findById(member.getId()).get();

        // Then
        Assertions.assertThat(findMember.getId()).isEqualTo(memberA.getId());
        Assertions.assertThat(findMember.getUsername()).isEqualTo(memberA.getUsername());
    }

    @Test
    public void testProduct() throws Exception {
        // Given
        Product productA = new Product("productA", 5000);

        // When
        Product product     = productRepository.save(productA);
        Product findProduct = productRepository.findById(product.getId()).get();

        // Then
        Assertions.assertThat(findProduct.getId()).isEqualTo(productA.getId());
    }
}

Test 결과

더보기

2022-02-20 22:22:22.968  INFO 20276 --- [           main] c.s.s.s.repository.MemberRepositoryTest  : Starting MemberRepositoryTest using Java 11.0.14 on DESKTOP-M8928OS with PID 20276 (started by [USER] in C:\project\workspace\springboot)
2022-02-20 22:22:22.968 DEBUG 20276 --- [           main] c.s.s.s.repository.MemberRepositoryTest  : Running with Spring Boot v2.6.3, Spring v5.3.15
2022-02-20 22:22:22.968  INFO 20276 --- [           main] c.s.s.s.repository.MemberRepositoryTest  : The following profiles are active: local
2022-02-20 22:22:23.252  INFO 20276 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-02-20 22:22:23.284  INFO 20276 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 37 ms. Found 2 JPA repository interfaces.
2022-02-20 22:22:23.346  INFO 20276 --- [           main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
2022-02-20 22:22:23.772  INFO 20276 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:h2:mem:bdf29e5f-dc85-4c91-9188-25c97977df6a;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
2022-02-20 22:22:24.040  INFO 20276 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-02-20 22:22:24.076  INFO 20276 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.4.Final
2022-02-20 22:22:24.186  INFO 20276 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-02-20 22:22:24.297  INFO 20276 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2022-02-20 22:22:24.344 DEBUG 20276 --- [           main] o.h.type.spi.TypeConfiguration$Scope     : Scoping TypeConfiguration [org.hibernate.type.spi.TypeConfiguration@bb8ead8] to MetadataBuildingContext [org.hibernate.boot.internal.MetadataBuildingContextRootImpl@5b44318]
2022-02-20 22:22:24.517 DEBUG 20276 --- [           main] o.h.type.spi.TypeConfiguration$Scope     : Scoping TypeConfiguration [org.hibernate.type.spi.TypeConfiguration@bb8ead8] to SessionFactoryImpl [org.hibernate.internal.SessionFactoryImpl@7ed8b44]
2022-02-20 22:22:24.732 DEBUG 20276 --- [           main] org.hibernate.SQL                        : drop table if exists hello CASCADE 
Hibernate: drop table if exists hello CASCADE 
2022-02-20 22:22:24.732 DEBUG 20276 --- [           main] org.hibernate.SQL                        : drop table if exists member CASCADE 
Hibernate: drop table if exists member CASCADE 
2022-02-20 22:22:24.732 DEBUG 20276 --- [           main] org.hibernate.SQL                        : drop table if exists product CASCADE 
Hibernate: drop table if exists product CASCADE 
2022-02-20 22:22:24.732 DEBUG 20276 --- [           main] org.hibernate.SQL                        : drop sequence if exists hibernate_sequence
Hibernate: drop sequence if exists hibernate_sequence
2022-02-20 22:22:24.737 DEBUG 20276 --- [           main] org.hibernate.SQL                        : create sequence hibernate_sequence start with 1 increment by 1
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
2022-02-20 22:22:24.737 DEBUG 20276 --- [           main] org.hibernate.SQL                        : create table hello (id bigint not null, primary key (id))
Hibernate: create table hello (id bigint not null, primary key (id))
2022-02-20 22:22:24.737 DEBUG 20276 --- [           main] org.hibernate.SQL                        : create table member (id bigint generated by default as identity, password varchar(255), username varchar(255), primary key (id))
Hibernate: create table member (id bigint generated by default as identity, password varchar(255), username varchar(255), primary key (id))
2022-02-20 22:22:24.737 DEBUG 20276 --- [           main] org.hibernate.SQL                        : create table product (id bigint generated by default as identity, name varchar(255), price double not null, primary key (id))
Hibernate: create table product (id bigint generated by default as identity, name varchar(255), price double not null, primary key (id))
2022-02-20 22:22:24.747  INFO 20276 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-02-20 22:22:24.747 TRACE 20276 --- [           main] o.h.type.spi.TypeConfiguration$Scope     : Handling #sessionFactoryCreated from [org.hibernate.internal.SessionFactoryImpl@7ed8b44] for TypeConfiguration
2022-02-20 22:22:24.754  INFO 20276 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-02-20 22:22:25.083  INFO 20276 --- [           main] c.s.s.s.repository.MemberRepositoryTest  : Started MemberRepositoryTest in 2.546 seconds (JVM running for 3.317)
2022-02-20 22:22:25.105  INFO 20276 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@7a560583 testClass = MemberRepositoryTest, testInstance = com.study.springboot.system.repository.MemberRepositoryTest@77d2e85, testMethod = testProduct@MemberRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@4d722ac9 testClass = MemberRepositoryTest, locations = '{}', classes = '{class com.study.springboot.SpringbootApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@53f0a4cb key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3899782c, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4b23c30a, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@602e0143, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@34c01041, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@d7f8e431, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@4b79ac84, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@2b80497f]; rollback [true]
2022-02-20 22:22:25.234 DEBUG 20276 --- [           main] org.hibernate.SQL                        : insert into product (id, name, price) values (null, ?, ?)
Hibernate: insert into product (id, name, price) values (null, ?, ?)
2022-02-20 22:22:25.234 TRACE 20276 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [productA]
2022-02-20 22:22:25.234 TRACE 20276 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [DOUBLE] - [5000.0]
2022-02-20 22:22:25.341  INFO 20276 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@7a560583 testClass = MemberRepositoryTest, testInstance = com.study.springboot.system.repository.MemberRepositoryTest@77d2e85, testMethod = testProduct@MemberRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@4d722ac9 testClass = MemberRepositoryTest, locations = '{}', classes = '{class com.study.springboot.SpringbootApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@53f0a4cb key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3899782c, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4b23c30a, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@602e0143, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@34c01041, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@d7f8e431, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@4b79ac84, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
2022-02-20 22:22:25.357  INFO 20276 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@7a560583 testClass = MemberRepositoryTest, testInstance = com.study.springboot.system.repository.MemberRepositoryTest@56a72887, testMethod = testMember@MemberRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@4d722ac9 testClass = MemberRepositoryTest, locations = '{}', classes = '{class com.study.springboot.SpringbootApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@53f0a4cb key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3899782c, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4b23c30a, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@602e0143, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@34c01041, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@d7f8e431, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@4b79ac84, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@2b80497f]; rollback [true]
2022-02-20 22:22:25.357 DEBUG 20276 --- [           main] org.hibernate.SQL                        : insert into member (id, password, username) values (null, ?, ?)
Hibernate: insert into member (id, password, username) values (null, ?, ?)
2022-02-20 22:22:25.357 TRACE 20276 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - []
2022-02-20 22:22:25.357 TRACE 20276 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] - [memberA]
2022-02-20 22:22:25.372  INFO 20276 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@7a560583 testClass = MemberRepositoryTest, testInstance = com.study.springboot.system.repository.MemberRepositoryTest@56a72887, testMethod = testMember@MemberRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@4d722ac9 testClass = MemberRepositoryTest, locations = '{}', classes = '{class com.study.springboot.SpringbootApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@53f0a4cb key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3899782c, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4b23c30a, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@602e0143, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@34c01041, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@d7f8e431, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@4b79ac84, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
2022-02-20 22:22:25.388  INFO 20276 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-02-20 22:22:25.388 TRACE 20276 --- [ionShutdownHook] o.h.type.spi.TypeConfiguration$Scope     : Handling #sessionFactoryClosed from [org.hibernate.internal.SessionFactoryImpl@7ed8b44] for TypeConfiguration
2022-02-20 22:22:25.388 DEBUG 20276 --- [ionShutdownHook] o.h.type.spi.TypeConfiguration$Scope     : Un-scoping TypeConfiguration [org.hibernate.type.spi.TypeConfiguration$Scope@44555ed2] from SessionFactory [org.hibernate.internal.SessionFactoryImpl@7ed8b44]

 


참고

[Major DB Dialect]
Oracle(any) : org.hibernate.dialect.OracleDialect
Oracle10g : org.hibernate.dialect.Oracle10gDialect
MySql, MariaDB : org.hibernate.dialect.MySQL5Dialect
MsSql2000 : org.hibernate.dialect.SQLServerDialect 
MsSql2005 : org.hibernate.dialect.SQLServer2005Dialect
MsSql2008 : org.hibernate.dialect.SQLServer2008Dialect

[hbm2ddl.auto options]
update : 객체와 스키마 비교, 기존 스키마 유지, 추가/삭제만 진행
create : 시작 시 스키마 삭제, 새로 생성
create-drop : SessionFactory 종료 시 스키마 삭제

https://hermeslog.tistory.com/570

 

[Exception] Multi Database 시 Bean 클래스 Repository Call 오류

개발환경 1. STS 버전 : 4.13.1 2. JDK 버전 : OpenJDK 11.0.14_9_x64 3. Tomcat 버전 : 9.0.56 4. Maven 버전 : 3.8.4 5. Spring 버전 : Spring Boot 2.6.3 6. Database : Docker 에 DB 설치 - primary - Postgre..

hermeslog.tistory.com


참고

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

https://www.javachinna.com/spring-boot-multiple-data-sources/

 

How to Configure Multiple Data Sources, Entity Managers, Transaction Managers in Spring Boot - JAVA CHINNA

Configure Multiple Data Sources, Entity Managers, Transaction Managers, Connection Pool and autowire them for CRUD operations in Spring Boot

www.javachinna.com

https://mudchobo.github.io/posts/spring-boot-jpa-multiple-database

 

Spring Boot JPA - multiple database 설정. - mudchobo devlog

리플리케이션 되어 있는 디비에서 서비스쪽에서는 전부 마스터, 통계와 같이 슬로우쿼리가 걸리는 애들은 슬레이브로 쿼리를 날리기 위해서 여기까지 왔다. 역시 이 방법이 제일 맘에 드는 것

mudchobo.github.io

https://programmer-chocho.tistory.com/78

 

QueryDSL + multi data source 연동하기

1.QueryDSL + single data source 인 경우 DataSourceConfiguration - entityManagerFactory 생성 메서드 - 데이터소스 클래스를 생성하는 것이 주 내용이 아니기 때문에 entityManagerFactory 생성 메소드만 올린..

programmer-chocho.tistory.com

https://www.techgeeknext.com/spring-boot/spring-boot-multiple-datasources-jpa

 

TechGeekNext - Next Generation Tech, Reviews and Tips

Adblocker detected! Please consider whitelist or disable this site. We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading. To keep the site operating, we need funding, and practical

www.techgeeknext.com

 

 

 

728x90