Springboot连接两个数据库(以Mysql和H2数据库为例)
在Spring Boot中,你可以配置多个数据源以连接两个不同的数据库。以下是一个配置两个数据源(Mysql和H2)的示例:
- 在
application.properties
或application.yml
中配置两个数据源的基本属性:
# Mysql 数据源配置
spring.datasource.mysql.jdbc-url=jdbc:mysql://localhost:3306/mydb
spring.datasource.mysql.username=root
spring.datasource.mysql.password=yourpassword
spring.datasource.mysql.driver-class-name=com.mysql.cj.jdbc.Driver
# H2 数据源配置
spring.datasource.h2.url=jdbc:h2:mem:testdb
spring.datasource.h2.driver-class-name=org.h2.Driver
spring.datasource.h2.username=sa
spring.datasource.h2.password=
- 配置两个
DataSource
Bean:
@Configuration
public class DataSourceConfig {
@Bean(name = "mysqlDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.mysql")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "h2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.h2")
public DataSource h2DataSource() {
return DataSourceBuilder.create().build();
}
}
- 配置两个
JpaRepository
接口,分别使用@EnableJpaRepositories
注解指定不同的数据源:
@EnableJpaRepositories(
basePackages = "com.yourpackage.mysql",
entityManagerFactoryRef = "mysqlEntityManager",
transactionManagerRef = "mysqlTransactionManager"
)
public class MysqlConfig {
@Bean(name = "mysqlEntityManager")
@Primary
public LocalContainerEntityManagerFactoryBean mysqlEntityManager(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(mysqlDataSource())
.packages("com.yourpackage.mysql")
.persistenceUnit("mysql")
.build();
}
@Bean(name = "mysqlTransactionManager")
@Primary
public PlatformTransactionManager mysqlTransactionManager(
@Qualifier("mysqlEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
@EnableJpaRepositories(
basePackages = "com.yourpackage.h2",
entityManagerFactoryRef = "h2EntityManager",
transactionManagerRef = "h2TransactionManager"
)
public class H2Config {
@Bean(name = "h2EntityManager
评论已关闭