Configure Relational and Non-relational Databases in the same project with Spring-Data + Hibernate

Asked

Viewed 134 times

2

I am trying to create a Java application where I need to configure two databases: Mongodb and Mysql. My idea is to use Spring-Data with Hibernate for both banks, but I found only tutorials for setting up Cross-Store between banks.

Is there any way I can configure my templates so that each one is persisted in the database I configure in XML?

  • I have been through the same difficulty as you, however my case was to connect in two different relational banks (oracle and postgre) with each one with its entities. I did a lot of research, but I didn’t find anything either. I opened a question in the English OS and I got no answer. So I had to abandon this solution, but still want to know if this is possible with Spring Data.

  • I believe this is possible using a configuration similar to this https://gist.github.com/efraimcf/0af2cc68bfcdfbde55be I have read about some situations where they configured differently, as in this thread: http://stackoverflow.com/questions/13877734/hibernate-using-two-Different-database-schemas-in-the-same-application

  • I made this configuration. But how would you specify which EM the Spring Data Daos would use using the XML configuration?

  • In Hibernate it is already configured by Sessionfactory property packagesToScan ... With JPA, I believe the answer indicated by @utluiz below is the most appropriate

1 answer

1


Using class-based configuration and annotations it is possible to split the configuration of each Spring Data JPA repository and its respective DataSource in a separate configuration file.

This article have an example:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "barEntityManagerFactory", 
        transactionManagerRef = "barTransactionManager",
        basePackages = { "com.sctrcd.multidsdemo.integration.repositories.bar" })
public class BarConfig {

    @Autowired JpaVendorAdapter jpaVendorAdapter;

    @Bean(name = "barDataSource")
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
                .setName("bardb").setType(EmbeddedDatabaseType.HSQL).build();
    }

    @Bean(name = "barEntityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    ...

}

Then you’d do the same to FooConfig, that is, for the other configuration class that will set another DataSource, EntityManager and @EnableJpaRepositories.

Via XML the process would be identical. The important thing is that the EntityManager and the TransactionManager especificados em cada configuração de repositório apontem para oDatasource` desired.

  • Excellent @utluiz, I’ll do some tests here and comment again. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.