스프링부트) 2개의 데이터베이스 사용하기

2024. 6. 17. 15:54웹개발/스프링부트 - 데이터베이스

728x90

 레시피 관련 웹 어플리케이션을 만들었는데 포트폴리오가 부족하다는 생각이 들어 쇼핑몰도 구현하려고 한다. 만개의 레시피와 쇼핑몰을 참고해서 마리아DB를 사용해 레시피 용(enlacolocal)과 쇼핑몰(shopping) 데이터베이스를 구분해서 사용하려고 한다. 

 

참고:

 

[JPA/Querydsl] Multiple Databases(다중 DB) 설정하기

하나의 Spring 코드에서 여러 개의 DB를 사용해보자! 🌠

velog.io

 

 

 

[SpringBoot JPA] 다중 DB 설정하기 (multi Datasource + 이기종 DB)

간혹 사이트들을 연계해야 할때, 그 중에서도 api 없는 사이트의 데이터를 사용해야할 때, 하나의 웹에서 여러 DB를 연결 시켜 사용해야 할 때가 있다. 간단하게 DB Link 로 해결하려 했으나 메인으

jong-bae.tistory.com

 

 

 

2개 이상의 DB를 사용하는 Spring Boot 환경에서 Spring Data Jpa 사용시 트랜잭션 관련 에러

한 프로젝트에서 2개 이상의 DB를 연결해서 사용하기 위한 다중 DataSource 설정을 아래와 같이 했다. @Configuration @EnableTransactionManagement(proxyTargetClass = true) @EnableJpaRepositories( entityManagerFactoryRef = "aJpaEn

dncjf64.tistory.com

 

※ 큰 도움이 됩니다. 😊😊

 

우선 레시피 관련 데이터베이스는 생성이 돼있는 상태로 

<application.properties>

spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.jdbc-url=jdbc:mariadb: 레시피 주소
spring.datasource.username= abc
spring.datasource.password= 1234

 

위와 같이 설정이 돼있으며 JPA도 사용 중이었다. 그런데 찾아보니 JPA는 단일한 데이터베이스에서만 사용이 가능하고 2개 이상부터는 직접 설정을 해줘야 한다고 했다.

 

그래서 2개로 구분했다.

<application.properties>

#Recipe database
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.jdbc-url=jdbc:mariadb:// 레시피 주소
spring.datasource.username= abc
spring.datasource.password= 1234

#Shopping database 
spring.datasource2.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource2.jdbc-url=jdbc:mariadb:// 쇼핑몰 주소
spring.datasource2.username= abc
spring.datasource2.password= 1234

 

그리고 기존에 있던 appliction에서의 jpa 설정도 없앴다.

#JPA
#spring.jpa.hibernate.ddl-auto=update
#spring.jpa.database-platform=org.hibernate.dialect.MariaDB103Dialect
#spring.jpa.properties.hibernate.format_sql=true
#spring.jpa.properties.hibernate.show_sql=true

-- 모두 주석처리 --

 

<EnlacolocalDataSourceConfig>

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
@EnableJpaRepositories(
        basePackages = "com.example.enlaco.enlacolocal",
        entityManagerFactoryRef = "enlacolocalEntityManager",
        transactionManagerRef = "enlacolocalTransactionManager"
)
public class EnlacolocalDataSourceConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource enlacolocalDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean enlacolocalEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(enlacolocalDataSource());
        em.setPackagesToScan(new String[] {"엔티티 패키지 주소"});

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setShowSql(true);
        vendorAdapter.setGenerateDdl(true);
        em.setJpaVendorAdapter(vendorAdapter);

        HashMap<String, Object> prop = new HashMap<>();
        prop.put("hibernate.dialect", "org.hibernate.dialect.MariaDB103Dialect");
        prop.put("hibernate.hbm2ddl.auto", "update");
        prop.put("hibernate.format_sql", true);
        prop.put("hibernate.show_sql", true);
        em.setJpaPropertyMap(prop);

        return em;
    }

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

 

<ShoppingDataSourceConfig>

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = "com.example.enlaco.shopping",
        entityManagerFactoryRef = "shoppingEntityManager",
        transactionManagerRef = "shoppingTransactionManager"
)
public class ShoppingDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource2")
    public DataSource shoppingDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean shoppingEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(shoppingDataSource());
        em.setPackagesToScan(new String[] {"엔티티 패키지 주소"});

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setShowSql(true);
        vendorAdapter.setGenerateDdl(true);
        em.setJpaVendorAdapter(vendorAdapter);

        HashMap<String, Object> prop = new HashMap<>();
        prop.put("hibernate.dialect", "org.hibernate.dialect.MariaDB103Dialect");
        prop.put("hibernate.hbm2ddl.auto", "none");
        prop.put("hibernate.format_sql", true);
        prop.put("hibernate.show_sql", true);
        em.setJpaPropertyMap(prop);

        return em;
    }

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

 

그리고 Application에 추가 해주었다.

@EntityScan(basePackages = {"com.example.enlaco.enlacolocal.Entity", "com.example.enlaco.shopping.ShopEntity"})  // 여러 패키지 스캔

 

※ 지적 및 피드백 감사합니다.

'웹개발 > 스프링부트 - 데이터베이스' 카테고리의 다른 글

2403 - 1) sql 오류  (0) 2024.03.18