74.7 Use Two EntityManagers
Even if the default EntityManagerFactory
works fine, you will need to define a new one because otherwise the presence of the second bean of that type will switch off the default. To make it easy to do that you can use the convenient EntityManagerBuilder
provided by Spring Boot, or if you prefer you can just use the LocalContainerEntityManagerFactoryBean
directly from Spring ORM.
Example:
// add two data sources configured as above _@Bean_ public LocalContainerEntityManagerFactoryBean customerEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(customerDataSource()) .packages(Customer.class) .persistenceUnit("customers") .build(); } _@Bean_ public LocalContainerEntityManagerFactoryBean orderEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(orderDataSource()) .packages(Order.class) .persistenceUnit("orders") .build(); }
The configuration above almost works on its own. To complete the picture you need to configure TransactionManagers
for the two EntityManagers
as well. One of them could be picked up by the default JpaTransactionManager
in Spring Boot if you mark it as @Primary
. The other would have to be explicitly injected into a new instance. Or you might be able to use a JTA transaction manager spanning both.
If you are using Spring Data, you need to configure @EnableJpaRepositories
accordingly:
_@Configuration_ _@EnableJpaRepositories(basePackageClasses = Customer.class, entityManagerFactoryRef = "customerEntityManagerFactory")_ public class CustomerConfiguration { ... } _@Configuration_ _@EnableJpaRepositories(basePackageClasses = Order.class, entityManagerFactoryRef = "orderEntityManagerFactory")_ public class OrderConfiguration { ... }