Spring Data Jpa配置多数据源的方法
要在项目中为Spring Data JPA配置超过一个数据源,就需要创建多个Data Source Bean
和对应的EntityManagerFactory
.以下是创建步骤。
第1步 配置DataSource
在application.yaml
里添加:
spring:
datasource:
first:
url: jdbc:mysql://localhost:3306/first-db
username:
password:
driver-class-name: om.mysql.cj.jdbc.Driver
second:
url: jdbc:mysql://localhost:3306/second-db
username:
password:
driver-class-name: om.mysql.cj.jdbc.Driver
第2步 创建多个Data Source Bean
在配置中创建多个Data Source
Bean, 并使用@ConfigurationProperties
注解来绑定各个数据源的配置属性。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfigurer {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.first")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
}
第3步 配置EntityManagerFactory
创建多个EntityManagerFactory
bean,每个EntityManagerFactory
与一个DataSource
关联,并指定persistenceUnitName
以便在后续的JPA配置中使用。
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
@Configuration
public class JpaConfig {
@Bean
public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory(
JpaVendorAdapter jpaVendorAdapter, DataSource firstDataSource) {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(firstDataSource);
emf.setPackagesToScan("com.example.first.entity");
emf.setJpaVendorAdapter(jpaVendorAdapter);
emf.setPersistenceUnitName("firstEntityManager");
return emf;
}
@Bean
public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory(
JpaVendorAdapter jpaVendorAdapter, DataSource secondDataSource) {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(secondDataSource);
emf.setPackagesToScan("com.example.second.entity");
emf.setJpaVendorAdapter(jpaVendorAdapter);
emf.setPersistenceUnitName("secondEntityManager");
return emf;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
return new HibernateJpaVendorAdapter();
}
}
第4步 为每个数据源自定义Repository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface FirstEntityRepository extends JpaRepository<FirstEntity, Long> {
}
@Repository
public interface SecondEntityRepository extends JpaRepository<SecondEntity, Long> {
}
继承对应的Repository就可以实现不同数据源的查询了。
发表回复