springboot jpa 多数据源
时间: 2023-10-12 17:11:57 浏览: 72
springboot多数据源
Spring Boot支持多数据源配置,可以使用JPA来访问多个数据库。
首先需要在application.properties文件中配置数据源:
```
# 数据源1
spring.datasource.url=jdbc:mysql://localhost:3306/test1
spring.datasource.username=root
spring.datasource.password=root
# 数据源2
spring.datasource.test2.url=jdbc:mysql://localhost:3306/test2
spring.datasource.test2.username=root
spring.datasource.test2.password=root
```
然后在配置类中配置多个数据源:
```
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory1",
transactionManagerRef = "transactionManager1",
basePackages = { "com.example.repository1" })
public class DataSource1Config {
@Primary
@Bean(name = "dataSource1")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "entityManagerFactory1")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder, @Qualifier("dataSource1") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.entity1")
.persistenceUnit("dataSource1")
.build();
}
@Primary
@Bean(name = "transactionManager1")
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory1") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory2",
transactionManagerRef = "transactionManager2",
basePackages = { "com.example.repository2" })
public class DataSource2Config {
@Bean(name = "dataSource2")
@ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "entityManagerFactory2")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder, @Qualifier("dataSource2") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.entity2")
.persistenceUnit("dataSource2")
.build();
}
@Bean(name = "transactionManager2")
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory2") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
```
最后在服务类中指定使用哪个数据源:
```
@Service
@Transactional(transactionManager = "transactionManager1")
public class Service1 {
@Autowired
private Repository1 repository1;
// ...
}
@Service
@Transactional(transactionManager = "transactionManager2")
public class Service2 {
@Autowired
private Repository2 repository2;
// ...
}
```
以上就是使用Spring Boot和JPA实现多数据源的步骤。
阅读全文