mysql postgresql双数据源配置
在Spring Boot应用中配置MySQL和PostgreSQL双数据源,你可以使用Spring Data JPA和Hibernate。以下是一个基本的配置示例:
- 在
pom.xml
中添加MySQL和PostgreSQL的依赖:
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>Your MySQL version</version>
</dependency>
<!-- PostgreSQL -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>Your PostgreSQL version</version>
</dependency>
- 配置
application.properties
或application.yml
:
# MySQL
spring.datasource.mysql.url=jdbc:mysql://localhost:3306/your_mysql_db
spring.datasource.mysql.username=your_mysql_username
spring.datasource.mysql.password=your_mysql_password
# PostgreSQL
spring.datasource.pg.url=jdbc:postgresql://localhost:5432/your_pg_db
spring.datasource.pg.username=your_pg_username
spring.datasource.pg.password=your_pg_password
- 创建实体类和Repository接口,分别对应MySQL和PostgreSQL的数据模型。
- 配置双数据源:
@Configuration
public class DataSourceConfig {
@Bean(name = "mysqlDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.mysql")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "pgDataSource")
@ConfigurationProperties(prefix = "spring.datasource.pg")
public DataSource pgDataSource() {
return DataSourceBuilder.create().build();
}
}
- 配置JPA:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = "com.yourpackage.mysql.repository",
entityManagerFactoryRef = "mysqlEntityManager",
transactionManagerRef = "mysqlTransactionManager"
)
public class MySqlConfig {
@Primary
@Bean(name = "mysqlEntityManager")
public LocalContainerEntityManagerFactoryBean mysqlEntityManager(
EntityManagerFactoryBuilder builder,
@Qualifier("mysqlDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.yourpackage.mysql.entity")
.persistenceUnit("mysql")
.build();
}
@Primary
@Bean(name = "mysqlTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(
@Qualifier("mysqlEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManage
评论已关闭