아무거나

[Spring Boot] JPA DatasourceConfig 설정 (Multi Connection 또는 추가 설정시 유용) 본문

Java & Kotlin/JPA

[Spring Boot] JPA DatasourceConfig 설정 (Multi Connection 또는 추가 설정시 유용)

전봉근 2021. 6. 16. 16:00
반응형
  • Spring Boot 환경에서 DatasourceConfig 설정 (Multi Connection 또는 추가 설정시 유용)
    • DataSourceConfig 추가 [DataSourceConfig.java]
      package com.example.bkjeon.base.config;
      
      import java.util.HashMap;
      import javax.persistence.EntityManager;
      import javax.sql.DataSource;
      import lombok.RequiredArgsConstructor;
      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.core.env.Environment;
      import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
      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;
      
      @EnableJpaAuditing
      @Configuration
      @EnableJpaRepositories(
          basePackages = "com.example.bkjeon.base.repository",
          entityManagerFactoryRef = "baseEntityManager",
          transactionManagerRef = "baseTransactionManager"
      )
      @RequiredArgsConstructor
      public class DataSourceConfig {
      
          private static final String AES_KEY = "bkjeon!@";
      
          private final Environment env;
      
          @Bean
          @ConfigurationProperties(prefix = "spring.datasource")
          public DataSource getDataSource() {
              return DataSourceBuilder.create().build();
          }
      
          @Bean
          public LocalContainerEntityManagerFactoryBean baseEntityManager() {
              LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
              em.setDataSource(getDataSource());
              em.setPackagesToScan(new String[] {"kr.co.oliveyoung.auth.domain"});
      
              HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
              em.setJpaVendorAdapter(vendorAdapter);
      
              HashMap<String, Object> properties = new HashMap<>();
              properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
              properties.put("hibernate.dialect", env.getProperty("spring.jpa.database-platform"));
      
              String aesKey = System.getProperty("mysql.aeskey");
              if (aesKey == null || !AES_KEY.equals(aesKey)) {
                  throw new IllegalArgumentException(String.format("aeskey error!!: [%s]", aesKey));
              }
              properties.put("AES_KEY", aesKey);
      
              em.setJpaPropertyMap(properties);
      
              return em;
          }
      
          @Bean
          public PlatformTransactionManager baseTransactionManager() {
              JpaTransactionManager transactionManager = new JpaTransactionManager();
              transactionManager.setEntityManagerFactory(baseEntityManager().getObject());
      
              return transactionManager;
          }
      
      }    
      
    • Application.yml 설정 변경
      [application.yml]
      ...
        # H2 db
        spring:
          profiles: local-h2
          datasource:
            jdbcUrl: jdbc:h2:mem:testdb
            username: sa
            driverClassName: org.h2.Driver
            data: classpath:sql/data-h2.sql
          jpa:
            database-platform: org.hibernate.dialect.H2Dialect
            hibernate:
              ddl-auto: create-drop
          h2:
            console:
              enabled: true  
        # MySQL DB
        spring:
          profiles: local-db
          datasource:
            jdbcUrl: jdbc:mysql://127.0.0.1:3306/bkjeon_jpa?socketTimeout=30000&connectTimeout=30000&serverTimezone=Asia/Seoul&useUnicode=yes&characterEncoding=utf8
            username: bkjeon
            password: wjsqhdrms
            driverClassName: com.mysql.cj.jdbc.Driver
            data: classpath:sql/data-h2.sql
            initialization-mode: always
          jpa:
            database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
            hibernate:
              ddl-auto: create-drop      
      ...
      
반응형
Comments