복붙노트

[SPRING] 스프링 부트, 스프링 데이터 JPA 여러 데이터 소스 포함

SPRING

스프링 부트, 스프링 데이터 JPA 여러 데이터 소스 포함

각 @Repositories 봄 부팅 및 스프링 데이터 JPA 함께 다른 DataSource (s) 연결하려고합니다. 나는 다음과 같이 http://xantorohara.blogspot.com/2013/11/spring-boot-jdbc-with-multiple.html을 참조로 사용했다. 다음은 스프링 데이터 JPA를 사용하여 유사한 솔루션을 구현하기 위해 사용하고있는 코드입니다.

CustomerDbConfig.java (첫 번째 데이터 소스 연결)

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

    @Bean(name = "customerEntityManager")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] {"com.mm.domain.customer"});

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalJpaProperties());
        em.setPersistenceUnitName("customerPersistence");
        em.setPackagesToScan("com.mm.domain.customer");

        return em;
    }

    Properties additionalJpaProperties(){
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        properties.setProperty("hibernate.show_sql", "true");

        return properties;
    }

    @Bean
    public DataSource dataSource(){
        return DataSourceBuilder.create()
                .url("jdbc:h2:mem:customer:H2")
                .driverClassName("org.h2.Driver")
                .username("sa")
                .password("")
                .build();
    }   

    @Bean(name = "customerTransactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }
}

CustomerDbConfig.java (두 번째 데이터 소스)

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

    @Bean(name = "customerEntityManager")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] {"com.mm.domain.customer"});

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalJpaProperties());
        em.setPersistenceUnitName("customerPersistence");
        em.setPackagesToScan("com.mm.domain.customer");

        return em;
    }

    Properties additionalJpaProperties(){
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        properties.setProperty("hibernate.show_sql", "true");

        return properties;
    }

    @Bean
    public DataSource dataSource(){
        return DataSourceBuilder.create()
                .url("jdbc:h2:mem:customer:H2")
                .driverClassName("org.h2.Driver")
                .username("sa")
                .password("")
                .build();
    }   

    @Bean(name = "customerTransactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }
}

Customer.java (모델)

@Entity
@Table(name = "customer")
@Data
@EqualsAndHashCode(exclude = {"id"})
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "age", nullable = false)
    private Integer age;

....

Order.java (모델)

@Entity
@Table(name = "order")
@Data
@EqualsAndHashCode(exclude = {"id"})
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "code", nullable = false)
    private Integer code;

    @Column(name = "quality", nullable = false)
    private Integer quality;

...

CustomerRepository.java

public interface CustomerRepository extends JpaRepository<Customer, Integer>{

}

OrderRepository.java

public interface OrderRepository extends JpaRepository<Order, Integer> {

}

마지막으로, Application.java

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringApplication{

       public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }

        @Bean
        public ServletRegistrationBean h2Console() {
            ServletRegistrationBean reg = new ServletRegistrationBean(new WebServlet(), "/console/*");
            reg.setLoadOnStartup(1);
            return reg;
        }
}

시작하는 동안 다음 예외가 throw됩니다.

-10-10 15:45:24.757 ERROR 1549 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerTransactionManager' defined in class path resource [com/mm/boot/multidb/CustomerConfig.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [javax.persistence.EntityManagerFactory]: : No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: customerEntityManager,orderEntityManager; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: customerEntityManager,orderEntityManager
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:747)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:462)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
    at com.mm.boot.multidb.Application.main(Application.java:17)
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: customerEntityManager,orderEntityManager
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:974)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:811)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:739)
    ... 18 common frames omitted

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerTransactionManager' defined in class path resource [com/mm/boot/multidb/CustomerConfig.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [javax.persistence.EntityManagerFactory]: : No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: customerEntityManager,orderEntityManager; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: customerEntityManager,orderEntityManager
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:747)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:462)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
    at com.mm.boot.multidb.Application.main(Application.java:17)
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: customerEntityManager,orderEntityManager
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:974)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:811)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:739)
    ... 18 more

샘플의 전체 코드는 GitHub (https://github.com/tonym2105/samples/tree/master/boot-multidb-sample)에서 찾을 수 있습니다.

도와 주셔서 미리 감사드립니다.

해결법

  1. ==============================

    1.@EnableAutoConfiguration 및 application.properties를 사용하여 여러 데이터 소스를 갖는 또 다른 방법이 있습니다.

    @EnableAutoConfiguration 및 application.properties를 사용하여 여러 데이터 소스를 갖는 또 다른 방법이 있습니다.

    기본적으로 application.properties에 여러 dataSource 구성 정보를 입력하고 @EnableAutoConfiguration에 의해 첫 번째 dataSource에 대한 기본 설정 (dataSource 및 entityManagerFactory)을 자동으로 생성합니다. 그러나 다음 dataSource를 위해, 프로퍼티 파일의 정보로 수동으로 dataSource, entityManagerFactory 및 transactionManager를 생성하십시오.

    다음은 두 개의 데이터 소스를 설정하는 예제입니다. 첫 번째 dataSource는 @EnableAutoConfiguration에 의해 설정됩니다.이 설정은 여러 구성이 아닌 한 구성에서만 지정할 수 있습니다. 그러면 DataSourceTransactionManager에 의해 'transactionManager'가 생성되어 주석에 의해 생성 된 기본 transactionManager를 찾습니다. 그러나 트랜잭션을 기본 DataSourceTransactionManager에 대해서만 예약 된 스레드 풀에서 스레드에서 시작되지 않은 및 여러 트랜잭션 관리자가있을 때도 보지 못했습니다. 그래서 나는 'transactionManager'빈 이름과 기본 entityManagerFactory를 할당하여 첫 번째 dataSource에 대해서도 JpaTransactionManager에 의해 수동으로 transactionManager를 생성합니다. 첫 번째 dataSource의 JpaTransactionManager가 ScheduledThreadPool의 스레드에서 이상한 트랜잭션 문제를 확실하게 해결합니다.

    Spring Boot 1.3.0.RELEASE에 대한 업데이트

    기본 데이터 소스에 @EnableAutoConfiguration을 사용하여 이전 구성을 찾았습니다. Spring Boot 1.3 버전으로 entityManagerFactory를 찾는 데 문제가 있습니다. 어쩌면 기본 entityManagerFactory는 @EnableAutoConfiguration에 의해 생성되지 않습니다. 이제는 entityManagerFactory를 직접 작성합니다. 따라서 @EntityScan을 사용할 필요가 없습니다. 그래서 @EnableAutoConfiguration에 의해 점점 더 많은 설정을 얻고있는 것처럼 보입니다.

    두 번째 dataSource가 @EnableAutoConfiguration없이 설정되고 'anotherTransactionManager'가 수동으로 생성됩니다.

    PlatformTransactionManager에서 확장 된 여러 개의 transactionManager가 있으므로 각 @Transactional 어노테이션에서 사용할 transactionManager를 지정해야합니다

    기본 저장소 구성

    @Configuration
    @EnableTransactionManagement
    @EnableAutoConfiguration
    @EnableJpaRepositories(
            entityManagerFactoryRef = "entityManagerFactory",
            transactionManagerRef = "transactionManager",
            basePackages = {"com.mysource.repository"})
    public class RepositoryConfig {
        @Autowired
        JpaVendorAdapter jpaVendorAdapter;
    
        @Autowired
        DataSource dataSource;
    
        @Bean(name = "entityManager")
        public EntityManager entityManager() {
            return entityManagerFactory().createEntityManager();
        }
    
        @Primary
        @Bean(name = "entityManagerFactory")
        public EntityManagerFactory entityManagerFactory() {
            LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
            emf.setDataSource(dataSource);
            emf.setJpaVendorAdapter(jpaVendorAdapter);
            emf.setPackagesToScan("com.mysource.model");
            emf.setPersistenceUnitName("default");   // <- giving 'default' as name
            emf.afterPropertiesSet();
            return emf.getObject();
        }
    
        @Bean(name = "transactionManager")
        public PlatformTransactionManager transactionManager() {
            JpaTransactionManager tm = new JpaTransactionManager();
            tm.setEntityManagerFactory(entityManagerFactory());
            return tm;
        }
    }
    

    다른 저장소 구성

    @Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(
            entityManagerFactoryRef = "anotherEntityManagerFactory",
            transactionManagerRef = "anotherTransactionManager",
            basePackages = {"com.mysource.anothersource.repository"})
    public class AnotherRepositoryConfig {
        @Autowired
        JpaVendorAdapter jpaVendorAdapter;
    
        @Value("${another.datasource.url}")
        private String databaseUrl;
    
        @Value("${another.datasource.username}")
        private String username;
    
        @Value("${another.datasource.password}")
        private String password;
    
        @Value("${another.dataource.driverClassName}")
        private String driverClassName;
    
        @Value("${another.datasource.hibernate.dialect}")
        private String dialect;
    
        public DataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
            dataSource.setDriverClassName(driverClassName);
            return dataSource;
        }
    
        @Bean(name = "anotherEntityManager")
        public EntityManager entityManager() {
            return entityManagerFactory().createEntityManager();
        }
    
        @Bean(name = "anotherEntityManagerFactory")
        public EntityManagerFactory entityManagerFactory() {
            Properties properties = new Properties();
            properties.setProperty("hibernate.dialect", dialect);
    
            LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
            emf.setDataSource(dataSource());
            emf.setJpaVendorAdapter(jpaVendorAdapter);
            emf.setPackagesToScan("com.mysource.anothersource.model");   // <- package for entities
            emf.setPersistenceUnitName("anotherPersistenceUnit");
            emf.setJpaProperties(properties);
            emf.afterPropertiesSet();
            return emf.getObject();
        }
    
        @Bean(name = "anotherTransactionManager")
        public PlatformTransactionManager transactionManager() {
            return new JpaTransactionManager(entityManagerFactory());
        }
    }
    

    application.properties

    # database configuration
    spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
    spring.datasource.username=sa
    spring.datasource.password=
    spring.datasource.driver-class-name=org.h2.Driver
    spring.datasource.continueOnError=true
    spring.datasource.initialize=false
    
    # another database configuration
    another.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=another;
    another.datasource.username=username
    another.datasource.password=
    another.datasource.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect 
    another.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
    

    @ Transactional annotation에 적합한 transactionManager 선택

    첫 번째 데이터 소스에 대한 서비스

    @Service("mainService")
    @Transactional("transactionManager")
    public class DefaultDataSourceServiceImpl implements DefaultDataSourceService       
    {
    
       //
    
    }
    

    다른 데이터 소스에 대한 서비스

    @Service("anotherService")
    @Transactional("anotherTransactionManager")
    public class AnotherDataSourceServiceImpl implements AnotherDataSourceService 
    {
    
       //
    
    }
    
  2. ==============================

    2.여기 내 해결책이다. spring-boot.1.2.5.RELEASE 기반.

    여기 내 해결책이다. spring-boot.1.2.5.RELEASE 기반.

    first.datasource.driver-class-name=com.mysql.jdbc.Driver
    first.datasource.url=jdbc:mysql://127.0.0.1:3306/test
    first.datasource.username=
    first.datasource.password=
    first.datasource.validation-query=select 1
    
    second.datasource.driver-class-name=com.mysql.jdbc.Driver
    second.datasource.url=jdbc:mysql://127.0.0.1:3306/test2
    second.datasource.username=
    second.datasource.password=
    second.datasource.validation-query=select 1
    
    @Configuration
    public class DataSourceConfig {
        @Bean
        @Primary
        @ConfigurationProperties(prefix="first.datasource")
        public DataSource firstDataSource() {
            DataSource ds =  DataSourceBuilder.create().build();
            return ds;
        }
    
        @Bean
        @ConfigurationProperties(prefix="second.datasource")
        public DataSource secondDataSource() {
            DataSource ds =  DataSourceBuilder.create().build();
            return ds;
        }
    }
    
  3. ==============================

    3.GitHub에서 제공 한 소스 코드를 확인했습니다. 구성에 몇 가지 실수 / 오타가있었습니다.

    GitHub에서 제공 한 소스 코드를 확인했습니다. 구성에 몇 가지 실수 / 오타가있었습니다.

    CustomerDbConfig / OrderDbConfig에서 customerEntityManager를 참조해야하며 패키지는 기존 패키지를 가리켜 야합니다.

    @Configuration
    @EnableJpaRepositories(
        entityManagerFactoryRef = "customerEntityManager",
        transactionManagerRef = "customerTransactionManager",
        basePackages = {"com.mm.boot.multidb.repository.customer"})
    public class CustomerDbConfig {
    

    customerEntityManager 및 orderEntityManager에서 스캔 할 패키지가 모두 적절한 패키지를 가리키고 있지 않습니다.

    em.setPackagesToScan("com.mm.boot.multidb.model.customer");
    

    또한 적절한 EntityManagerFactory의 삽입이 작동하지 않았습니다. 그것은해야한다:

    @Bean(name = "customerTransactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory customerEntityManager){
    
    }
    

    위의 문제와 예외가 발생했습니다. @Bean 메서드에서 이름을 제공하는 동안 적절한 EMF가 주입되도록해야합니다.

    내가 한 마지막 작업은 Jpa 저장소의 자동 구성을 비활성화하는 것입니다.

    @EnableAutoConfiguration(exclude = JpaRepositoriesAutoConfiguration.class)
    

    모든 수정 사항을 적용하면 응용 프로그램이 예상대로 시작됩니다!

  4. ==============================

    4.Steve Park와 Rafal Borowiec의 답변 덕분에 코드가 작동했지만 한 가지 문제가있었습니다. DriverManagerDataSource는 "간단한"구현이며 ConnectionPool을 제공하지 않습니다 (http://docs.spring.io/를 확인하십시오). spring / docs / current / javadoc-api / org / springframework / jdbc / datasource / DriverManagerDataSource.html).

    Steve Park와 Rafal Borowiec의 답변 덕분에 코드가 작동했지만 한 가지 문제가있었습니다. DriverManagerDataSource는 "간단한"구현이며 ConnectionPool을 제공하지 않습니다 (http://docs.spring.io/를 확인하십시오). spring / docs / current / javadoc-api / org / springframework / jdbc / datasource / DriverManagerDataSource.html).

    따라서 secondDB의 DataSource를 반환하는 함수를 대체했습니다.

    public DataSource <secondaryDB>DataSource() {
        // use DataSourceBuilder and NOT DriverManagerDataSource 
        // as this would NOT give you ConnectionPool
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(databaseUrl);
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);
        dataSourceBuilder.driverClassName(driverClassName);
        return dataSourceBuilder.build();
    }
    

    또한 EntityManager가 필요하지 않은 경우 entityManager ()와 @Bean 주석을 모두 제거 할 수 있습니다.

    또한 구성 클래스의 basePackages 주석을 제거 할 수도 있습니다. factoryBean.setPackagesToScan () 호출로 유지 관리하면됩니다.

  5. ==============================

    5.이유는 모르지만 작동합니다. 두 가지 구성이 동일합니다. xxx를 이름으로 변경하십시오.

    이유는 모르지만 작동합니다. 두 가지 구성이 동일합니다. xxx를 이름으로 변경하십시오.

    @Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(
        entityManagerFactoryRef = "xxxEntityManager",
        transactionManagerRef = "xxxTransactionManager",
        basePackages = {"aaa.xxx"})
     public class RepositoryConfig {
    @Autowired
    private Environment env;
    
    @Bean
    @Primary
    @ConfigurationProperties(prefix="datasource.xxx")
    public DataSource xxxDataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean
    public LocalContainerEntityManagerFactoryBean xxxEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(xxxDataSource());
        em.setPackagesToScan(new String[] {"aaa.xxx"});
    
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<String, Object>();
        properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
        em.setJpaPropertyMap(properties);
    
        return em;
    }
    
    @Bean(name = "xxxTransactionManager")
    public PlatformTransactionManager xxxTransactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(xxxEntityManager().getObject());
        return tm;
    }
    

    }

  6. from https://stackoverflow.com/questions/26308035/spring-boot-spring-data-jpa-with-multiple-datasources by cc-by-sa and MIT license