"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Spring Boot 및 Spring Data JPA를 사용하여 어떻게 여러 데이터 소스에 연결할 수 있나요?

Spring Boot 및 Spring Data JPA를 사용하여 어떻게 여러 데이터 소스에 연결할 수 있나요?

2024년 10월 31일에 게시됨
검색:181

How can I use Spring Boot and Spring Data JPA to connect to multiple data sources?

Spring Boot, 여러 데이터 소스가 있는 Spring Data JPA

Spring Boot 및 Spring Data JPA를 사용하여 여러 데이터 소스에 연결할 수 있습니다. 이를 수행하려면 @EnableJpaRepositories 주석을 사용하여 저장소의 기본 패키지를 지정하고 @EnableTransactionManagement 주석을 사용하여 트랜잭션 관리를 활성화할 수 있습니다. 그런 다음 리포지토리 메서드에서 @Transactional 주석을 사용하여 각 메서드에 사용할 데이터 소스를 지정할 수 있습니다.

예를 들어 다음 코드는 두 개의 데이터 소스에 연결하도록 Spring Boot를 구성하는 방법을 보여줍니다.

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "orderEntityManager",
        transactionManagerRef = "orderTransactionManager",
        basePackages = {"com.mm.repository.customer"})
public class CustomerDbConfig {

    @Bean(name = "customerEntityManager")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
        // ...
    }

    // ...
}

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "orderEntityManager",
        transactionManagerRef = "orderTransactionManager",
        basePackages = {"com.mm.repository.order"})
public class OrderDbConfig {

    @Bean(name = "orderEntityManager")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
        // ...
    }

    // ...
}

이 코드는 각 데이터 소스에 하나씩 두 개의 EntityManagerFactory Bean을 생성합니다. 그런 다음 저장소 메소드의 @Transactional 주석은 각 메소드에 사용할 EntityManagerFactory를 지정합니다. 예를 들어, 다음 코드는 @Transactional 주석을 사용하여 findCustomer 메소드가 customerEntityManager Bean을 사용해야 함을 지정하는 방법을 보여줍니다.

@Repository
public interface CustomerRepository {

    @Transactional(value = "customerEntityManager")
    Customer findCustomer(Integer id);

    // ...
}

예외

여러 데이터 소스에 연결하려고 할 때 예외가 발생하는 경우 다음을 확인하는 것이 중요합니다.

  • @EnableJpaRepositories가 및 @EnableTransactionManagement 주석이 구성 클래스에 있습니다.
  • @Transactional 주석이 저장소 메소드에 있고 사용할 올바른 EntityManagerFactory Bean을 지정하는지 확인하십시오.
  • 예외를 검사하십시오. 문제의 원인을 파악하려면 자세히 메시지를 보내세요.
릴리스 선언문 이 글은 1729758348에서 재인쇄되었습니다. 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3