Springboot项目连接多数据源(MySQL和SQLServer)
在Spring Boot项目中连接多数据源,你可以使用Spring Data JPA或者MyBatis。以下是使用Spring Data JPA连接MySQL和SQL Server的示例配置。
- 在
application.properties
或application.yml
中配置两个数据源的基本属性:
# MySQL 数据源配置
spring.datasource.mysql.jdbc-url=jdbc:mysql://localhost:3306/db_mysql
spring.datasource.mysql.username=root
spring.datasource.mysql.password=yourpassword
# SQL Server 数据源配置
spring.datasource.sqlserver.jdbc-url=jdbc:sqlserver://localhost:1433;databaseName=db_sqlserver
spring.datasource.sqlserver.username=yourusername
spring.datasource.sqlserver.password=yourpassword
- 配置两个
LocalContainerEntityManagerFactoryBean
,一个对应MySQL,一个对应SQL Server:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "mysqlEntityManager",
basePackages = {"com.yourpackage.mysql.repository"}
)
public class MysqlDataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.mysql")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean mysqlEntityManager(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(mysqlDataSource())
.packages("com.yourpackage.mysql.entity") // 设置实体类所在位置
.persistenceUnit("mysql")
.build();
}
@Bean
@Primary
public PlatformTransactionManager mysqlTransactionManager(
@Qualifier("mysqlEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "sqlserverEntityManager",
basePackages = {"com.yourpackage.sqlserver.repository"}
)
public class SqlserverDataSourceConfig {
@Bean
public DataSource sqlserverDataSo
评论已关闭