Spring JPA-Multiple Databases多数据源配置

本教程详细介绍了如何在Spring Data JPA系统中配置多个数据库。内容包括创建独立数据库的实体、JPA Repositories的设定、使用Java配置JPA以及在Spring Boot中设置多数据源的步骤,并提供了简单的测试案例。
摘要由CSDN通过智能技术生成

概括

在本教程中,我能将为具有多个数据库的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;
}

第二个实体,Productentity。

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值