java – Spring Boot JPA cant set up to work with two DataSource

Question:

I actually went through all the solutions, not sure what to do.

Purpose: to set up work with two data sources

spring.datasource.url=jdbc:h2:file:C://new_workspace//Database//db1.db
spring.datasource.username=sa1
spring.datasource.password=sa2
spring.datasource.driver-class-name=org.h2.Driver

datasource.s.url=jdbc:h2:file:C://new_workspace//Database//db2.db
datasource.s.username=sa2
datasource.s.password=sa2
datasource.s.driver-class-name=org.h2.Driver

spring.jpa.properties.hibernate.enable_lazy_load_no_trans = true
spring.jpa.hibernate.ddl-auto=none
  1. Create @primary Config (don't pay attention to the name – second, I put / rearranged annotations, etc.)

     @Configuration @EnableJpaRepositories(basePackages = "ru.ds.repsecond") public class SecondDataSource { @ConfigurationProperties(prefix = "datasource.s") @Primary @Bean public DataSource sDataSource(){ return DataSourceBuilder.create().build(); } }

Everything is fine here, I create a CrudRepository:

    public interface HobbyRepository extends CrudRepository<NhobbyEntity, Long>         {

}

in the controller it is picked up, everything is fine.

@Autowired
HobbyRepository hobbyRepository;

@RequestMapping(value = "/", method = RequestMethod.GET)
public Iterable<NhobbyEntity> getIndex(){
    Iterable<NhobbyEntity> entities = hobbyRepository.findAll();

    return entities;
}

I want to connect the second one, I do it as in the official documentation:

@Configuration

@EnableJpaRepositories(basePackages = "ru.ds.repfirst"
)
public class FirstDataSource {

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

}

Конфиг не подхватывается (с аннотацией - автоконфиг тоже). Т.е. подключение ко второй БД не идет.


И все репозитории, вроде как описанные как для второй БД подключаются к       первой.

I began to look at the solutions further, I saw that everyone was implementing a standard bundle for the second DS: DS, EMF, TM

implemented:

@Configuration
//@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = "ru.ds.repfirst"
    ,                     entityManagerFactoryRef = "h2EntityManager"
    ,                     transactionManagerRef = "h2tm"
)
public class FirstDataSource {

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

@Bean(name="h2EntityManager")
public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(
        EntityManagerFactoryBuilder builder){
    return builder.dataSource(pDataSource())
            .packages("ru.ds.entities")
            .build();
}

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

    return transactionManager;
}

}

По крайней мере подключается к БД
При старте пишет:

org.springframework.beans.factory.BeanCreationException: Error creating bean
with name
‘org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter’:
Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
org.springframework.boot.autoconfigure.web.HttpMessageConverters
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.messageConverters;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
‘org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration’:
Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private final java.util.List
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration.converters;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name ‘mappingJackson2HttpMessageConverter’
defined in class path resource
[org/springframework/boot/autoconfigure/web/JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration.class]:
Unsatisfied dependency expressed through constructor argument with
index 0 of type [com.fasterxml.jackson.databind.ObjectMapper]: : Error
creating bean with name ‘objectMapper’ defined in class path resource
[org/springframework/boot/autoconfigure/data/rest/SpringBootRepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.fasterxml.jackson.databind.ObjectMapper]: Factory
method ‘objectMapper’ threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘resourceMappings’ defined in class path
resource
[org/springframework/boot/autoconfigure/data/rest/SpringBootRepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[org.springframework.data.rest.core.mapping.ResourceMappings]: Factory
method ‘resourceMappings’ threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘repositories’ defined in class path resource
[org/springframework/boot/autoconfigure/data/rest/SpringBootRepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[org.springframework.data.repository.support.Repositories]: Factory
method ‘repositories’ threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘hobbyRepository’: Cannot create inner bean
‘(inner bean)#73fe8e8d’ of type
[org.springframework.orm.jpa.SharedEntityManagerCreator] while setting
bean property ‘entityManager’; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘(inner bean)#73fe8e8d’: Cannot resolve
reference to bean ‘entityManagerFactory’ while setting constructor
argument; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named ‘entityManagerFactory’ is defined; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘objectMapper’ defined in class path resource
[org/springframework/boot/autoconfigure/data/rest/SpringBootRepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.fasterxml.jackson.databind.ObjectMapper]: Factory
method ‘objectMapper’ threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘resourceMappings’ defined in class path
resource
[org/springframework/boot/autoconfigure/data/rest/SpringBootRepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[org.springframework.data.rest.core.mapping.ResourceMappings]: Factory
method ‘resourceMappings’ threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘repositories’ defined in class path resource
[org/springframework/boot/autoconfigure/data/rest/SpringBootRepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[org.springframework.data.repository.support.Repositories]: Factory
method ‘repositories’ threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘hobbyRepository’: Cannot create inner bean
‘(inner bean)#73fe8e8d’ of type
[org.springframework.orm.jpa.SharedEntityManagerCreator] while setting
bean property ‘entityManager’; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name ‘(inner bean)#73fe8e8d’: Cannot resolve
reference to bean ‘entityManagerFactory’ while setting constructor
argument; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named ‘entityManagerFactory’ is defined

Думаю, что беда в автоконфигурации, отключаю:

@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class })

does not help, continues to swear.

I configure the main class completely myself. Nothing works.

I tried all the links and manuals, nothing works.

Can anyone have a working gist?

Answer:

I made a variant with 2 datasources on this dock http://www.baeldung.com/spring-data-jpa-multiple-databases . It worked. Only in this case it is necessary to separate the domain objects.

If you need to separate domain objects among all datasources, then the spring has https://spring.io/blog/2007/01/23/dynamic-datasource-routing/ Did option 1 datasource for writing to one database, another datasource for reads from several (synchronous replication was enabled in postgres). It worked. I searched the examples on the github by searching for the AbstractRoutingDataSource string.

Scroll to Top