Обратите внимание на конфигурации (прокомментированные как / * важные * /)
в OrderConfig
@Configuration
/* important */
@EnableJpaRepositories(entityManagerFactoryRef = "orderEntityManagerFactory",
transactionManagerRef = "orderTransactionManager")
class OrderConfig {
@Bean
PlatformTransactionManager orderTransactionManager() {
return new JpaTransactionManager(orderEntityManagerFactory().getObject());
}
@Bean
LocalContainerEntityManagerFactoryBean orderEntityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
/* important */
factoryBean.setDataSource(orderDataSource());
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setPackagesToScan(OrderConfig.class.getPackage().getName());
return factoryBean;
}
@Bean
DataSource orderDataSource() {
return new EmbeddedDatabaseBuilder().//
setType(EmbeddedDatabaseType.HSQL).//
setName("orders").//
build();
}
}
и CustomerConfig
@Configuration
/* important */
@EnableJpaRepositories(entityManagerFactoryRef = "customerEntityManagerFactory",
transactionManagerRef = "customerTransactionManager")
class CustomerConfig {
@Bean
PlatformTransactionManager customerTransactionManager() {
return new JpaTransactionManager(customerEntityManagerFactory().getObject());
}
@Bean
LocalContainerEntityManagerFactoryBean customerEntityManagerFactory() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
/* important */
factoryBean.setDataSource(customerDataSource());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
factoryBean.setPackagesToScan(CustomerConfig.class.getPackage().getName());
return factoryBean;
}
@Bean
DataSource customerDataSource() {
return new EmbeddedDatabaseBuilder().//
setType(EmbeddedDatabaseType.HSQL).//
setName("customers").//
build();
}
}
и, наконец, аннотация @Transactional
в DataInitializer
/* important */
@Transactional("customerTransactionManager")
public CustomerId initializeCustomer() {
return customers.save(new Customer("Dave", "Matthews")).getId();
}
использует customerTransactionManager
, настроенный в CustomerConfig
и,
/* important */
@Transactional("orderTransactionManager")
public Order initializeOrder(CustomerId customer) {
Assert.notNull(customer, "Customer identifier must not be null!");
Order order = new Order(customer);
order.add(new LineItem("Lakewood Guitar"));
return orders.save(order);
}
использует orderTransactionManager
, настроенный в OrderConfig
По сути, вы настраиваете разные datasources
, разные entityManagers
, разные transactionManagers
и обращаетесь к нимконкретно по вашему выбору.