SpringBoot3+JPA+MySQL实现多数据源的读写分离(基于EntityManagerFactory)
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
return new HibernateJpaVendorAdapter();
}
@Bean(name = "entityManagerFactoryPrimary")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
EntityManagerFactoryBuilder builder,
@Qualifier("primaryDataSource") DataSource primaryDataSource) {
return builder
.dataSource(primaryDataSource)
.packages("com.yourcompany.yourapp.domain.primary") // Set package names of your entities
.persistenceUnit("primary")
.properties(jpaProperties())
.build();
}
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(
EntityManagerFactoryBuilder builder,
@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
return builder
.dataSource(secondaryDataSource)
.packages("com.yourcompany.yourapp.domain.secondary") // Set package names of your entities
.persistenceUnit("secondary")
.properties(jpaProperties())
.build();
}
private Map<String, Object> jpaProperties() {
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
// Add other JPA properties as needed
return properties;
}
// ... 配置多个EntityManager
}
这个配置类定义了两个数据源(primary和secondary),并为每个数据源创建了一个LocalContainerEntityManagerFactoryBean
实例。通过指定不同的包名来区分不同数据源的实体类。同时,它展示了如何配置JPA属性(例如方言)。在实际应用中,你需要将com.yourcompany.yourapp.domain.primary
和com.yourcompany.yourapp.domain.secondary
替换为实际实体类所在的包路径。
评论已关闭