概括
在本教程中,我能将为具有多个数据库的Spring Data JPA系统实现一个简单的Spring配置。
Entities
首先,让我们在单独的数据库中创建两个简单的实体(Entity)。这是第一个User
entity。
package com.baeldung.multipledb.model.user;
@Entity
@Table(schema = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@Column(unique = true, nullable = false)
private String email;
private int age;
}
第二个实体,Product
entity。
package com.baeldung.multipledb.model.product;
@Entity
@Table(schema = "products")
public class Product {
@Id
private int id;
private String name;
private double price;
}
JPA Repositories
让我们看看两个JPA Repositories,UserRepository
package com.baeldung.multipledb.dao.user;
public interface UserRepository
extends JpaRepository<User, Integer> {
}
ProductRepository
package com.baeldung.multipledb.dao.product;
public interface ProductRepository
extends JpaRepository<Product, Integer> {
}
再次注意我们是如何在不同的packages中创建这两个Repositories的。
使用Java配置JPA
接下来,让我们进入实际的Spring configuration,我们将首先设置两个配置类,一个用于User
,一个用于Product
。
在每个配置类中,都需要为User
定义一下的接口
- DataSource
- EntityManagerFactory (userEntityManager)
- TransactionManager (userTransactionManager)
下面让我们看看User
配置类
@Configuration
@PropertySource({
"classpath:persistence-multiple-db.properties" })
@EnableJpaRepositories(
basePackages = "com.baeldung.multipledb.dao.user",
entityManagerFactoryRef = "userEntityManager",
transactionManagerRef = "userTransactionManager"
)
public class PersistenceUserConfiguration {
@Autowired
private Environment env;
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean userEntityManager() {
LocalContainerEntityManagerFactoryBean em
= new LocalContainerEntityManagerFactoryBean();
em.setDataSource(userDataSource());
em.setPackagesToScan(
new String[] {
"com.baeldung.multipledb.model.user" });
HibernateJpaVendorAdapter vendorAdapter
= new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap