본문 바로가기

Spring

Spring boot multiple database 설정 (mybatis+hikari)

728x90
반응형

application.properties 

spring.db1.datasource.hikari.driver-class-name=org.mariadb.jdbc.Driver
spring.db1.datasource.hikari.jdbc-url=jdbc:mariadb://localhost:3306/db1?characterEncoding=UTF-8
spring.db1.datasource.hikari.username=admin
spring.db1.datasource.hikari.password=P!ssw0rd
spring.db1.datasource.hikari.connectionTimeout=5000
spring.db1.datasource.hikari.validationTimeout=1000
spring.db1.datasource.hikari.maximumPoolSize=10
spring.db1.datasource.hikari.max-lifetime=595000

spring.db2.datasource.hikari.driver-class-name=org.mariadb.jdbc.Driver
spring.db2.datasource.hikari.jdbc-url=jdbc:mariadb://localhost:3306/db2?characterEncoding=UTF-8
spring.db2.datasource.hikari.username=admin
spring.db2.datasource.hikari.password=P!ssw0rd
spring.db2.datasource.hikari.connectionTimeout=5000
spring.db2.datasource.hikari.validationTimeout=1000
spring.db2.datasource.hikari.maximumPoolSize=10
spring.db2.datasource.hikari.max-lifetime=595000

DB설정을 두 가지 해줘야한다.

중요한건 hikari datasource 연결이길 때문에 jdbc-url로 url을 지정해줘야한다.

Datasource가 하나일 때 url을 써도 되는 이유는 알아서 jdbc-url로 바꿔주기 때문에 하나일 때는 상관없지만 

두 개 이상일 경우 bean을 만들어서 지정해주기 때문에 jdbc-url로 써야함.

 

 

DB1. Config

@Configuration
// basePackes에 있는 Mapper에서 사용할 설정
// annotationClass를 지정하면 해당 어노테이션이 지정된 매퍼에서 사용가능 
@MapperScan(basePackages = {"com.heypli.app.test1.mapper", annotationClass = Database1.class
        , sqlSessionFactoryRef = "sqlSessionFactory")
@EnableTransactionManagement
public class DatabaseConfig {	
	// 여러 위치에 있는 매퍼를 사용할 때 
   final List<String> MAPPER_LOCATIONS_PATH = Arrays.asList("classpath:mapper/test1/*.xml", "classpath:mapper/common/*.xml");
   final String CONFIG_PATH        = "classpath:mybatis-config.xml";

// 기본으로 사용할 데이터소스에 @Primary를 넣어줘야함
    @Primary 
   @Bean(name="hikariConfig")
   @ConfigurationProperties(prefix="spring.db1.datasource.hikari")
   public HikariConfig hikariConfig() {
      return new HikariConfig();
   }

    @Primary
   @Bean(name="dataSource")
   public HikariDataSource hikariDataSource(@Autowired @Qualifier("hikariConfig") HikariConfig hikariConfig) throws Exception {
      HikariDataSource dataSource = new HikariDataSource(hikariConfig());
      return dataSource;
   }

    @Primary
    @Bean(name="sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(@Autowired @Qualifier("dataSource") DataSource dataSource, ApplicationContext applicationContext) throws Exception {

        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.heypli.app.test1.vo, com.heypli.app.common.vo");
        factoryBean.setConfigLocation(applicationContext.getResource(CONFIG_PATH));
        factoryBean.setMapperLocations(getResolverMapperLocations());

        return factoryBean.getObject();

    }

	// Resource를 만들어서 여러 위치에 있는 매퍼를 등록할 수 있다. 
    private Resource[] getResolverMapperLocations() throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        List<Resource> resources = new ArrayList<>();

        for(String location : MAPPER_LOCATIONS_PATH) {
            Resource[] mappers = resolver.getResources(location);
            resources.addAll(Arrays.asList(mappers));
        }
        return resources.toArray(new Resource[resources.size()]);
    }

    @Primary
    @Bean(name="sqlSession")
    public SqlSessionTemplate sqlSession(@Autowired @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Primary
    @Bean(name="transactionManager")
    public DataSourceTransactionManager transactionManager(@Autowired @Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

Database1.class

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Database1 {
    
}

어노테이션을 만들어서 매퍼에 사용할 수 있다.

Mapper.java

@Database1
public interface test1Mapper {

}

위처럼 매퍼에 어노테이션으로 적용가능 

 

 

DB1.Config

@Configuration
@MapperScan(value = "com.heypli.test2.mapper", annotationClass = Database2.class,
    sqlSessionFactoryRef = "commonSqlSessionFactory")
@EnableTransactionManagement
public class CommonDatabaseConfig {
   final String MAPPER_LOCATIONS_PATH = "classpath:mapper/test2/*.xml";
   final String CONFIG_PATH        = "classpath:mybatis-config.xml";
   
   @Bean(name="commonHikariConfig")
   @ConfigurationProperties(prefix="spring.common.datasource.hikari")
   public HikariConfig hikariConfig() {
      return new HikariConfig();
   }
   
   @Bean(name="commonDataSource")
   public HikariDataSource hikariDataSource(@Autowired @Qualifier("commonHikariConfig") HikariConfig hikariConfig) throws Exception {
      HikariDataSource dataSource = new HikariDataSource(hikariConfig());
      return dataSource;
   }
         
    @Bean(name="commonSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(@Autowired @Qualifier("commonDataSource") DataSource dataSource, ApplicationContext applicationContext) throws Exception {
       
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.heypli.test2.vo");
        factoryBean.setConfigLocation(applicationContext.getResource(CONFIG_PATH));
        factoryBean.setMapperLocations(applicationContext.getResources(MAPPER_LOCATIONS_PATH));
        
        return factoryBean.getObject();
        
    }
 
    @Bean(name="commonSqlSession")
    public SqlSessionTemplate sqlSession(@Autowired @Qualifier("commonSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
 
    @Bean(name="commonTransactionManager")
    public DataSourceTransactionManager transactionManager(@Autowired @Qualifier("commonDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

여기도 어노테이션 하나 인터페이스로 만들어서 사용할 매퍼에 써주면 된다.

 

 

참고로 스프링부트 + hikari + mybatis 연동 방법은 아래에 

 

https://tweety1121.tistory.com/entry/Spring-boot-mariadb-mybatis-hikaricp-%EC%84%A4%EC%A0%95

728x90
반응형