Spring Data JPA - Multiple EnableJpaRepositories

Viewed 103061

My application has multiple data sources , so i have created two data source configuration classes based on this URL .

But while running the spring boot application am getting error

Description: Field userDataRepo in com.cavion.services.UserDataService required a bean named 'entityManagerFactory' that could not be found. Action: Consider defining a bean named 'entityManagerFactory' in your configuration.

From this Question on StackOverflow helped me to figure out the issue.i need to specify the entityManagerFactoryRef on my JPA repositories .

But i have many repository classes some of them uses Entitymanager 'A' and some of them uses 'B' . my current spring boot application class is like this

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class })
@EnableTransactionManagement
@EntityScan("com.info.entity")
@ComponentScan({"com.info.services","com.info.restcontroller"})
@EnableJpaRepositories("com.info.repositories")
public class CavionApplication {

public static void main(String[] args) {
    SpringApplication.run(CavionApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }

    };
}}

I have given the EnableJpaRepositories on the spring boot class , so how can i configure multiple EnableJpaRepositories so that i can configure multiple entityManagerFactory ?

Please suggest the best way to setup the multiple data sources .

3 Answers

The answered provided by @Daniel C. is correct. Small correction/observation from my side.

  • @Primary is not required if you don't want to mark any datasource as default one, otherwise necessary.
  • If you are defining any of the EntityManagerFactoryBean with @Bean name as entityManagerFactory then it's better to mark it @Primary to avoid conflict.
  • @ConfigurationProperties("app.datasource.servers") can be marked at class level instead of defining at method level.
  • Better to return HikariDataSource as datasource if you using Spring Boot 2.x or higher version as it has been changed.
  • Make sure you define exact property for jdbc-url which is being used by HikariDataSource to refer JDBC Connection URL.
Related