You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot项目中配置PostgreSQL、MongoDB、MySQL多数据库

多数据源(MySQL+PostgreSQL+MongoDB)配置解决方案

项目结构

com.example.multidb
├── mysql
│   ├── entity
│   ├── repository
│   └── config
├── postgres
│   ├── entity
│   ├── repository
│   └── config
└── mongodb
    ├── document
    ├── repository
    └── config

Maven依赖(pom.xml)

<dependencies>
    <!-- Spring Boot Starter Data JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <!-- PostgreSQL驱动 -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.6.0</version>
    </dependency>

    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.34</version>
    </dependency>

    <!-- Spring Boot Starter Data MongoDB -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>

    <!-- 其他必要依赖 -->
    <!-- ... -->
</dependencies>

配置类设置

为每个数据库分别创建独立配置类,以下是修复后的完整配置:

PostgreSQL配置(com.example.multidb.postgres.config.PostgresConfig)

package com.example.multidb.postgres.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories(
    basePackages = "com.example.multidb.postgres.repository",
    entityManagerFactoryRef = "postgresEntityManagerFactory",
    transactionManagerRef = "postgresTransactionManager"
)
@EntityScan("com.example.multidb.postgres.entity")
public class PostgresConfig {

    @Autowired
    private EntityManagerFactoryBuilder builder;

    @Bean(name = "postgresDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.postgres")
    public DataSource postgresDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "postgresEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean postgresEntityManagerFactory(
            @Qualifier("postgresDataSource") DataSource dataSource) {
        return builder
                .dataSource(dataSource)
                .packages("com.example.multidb.postgres.entity")
                .persistenceUnit("postgres")
                .build();
    }

    @Bean(name = "postgresTransactionManager")
    public PlatformTransactionManager postgresTransactionManager(
            @Qualifier("postgresEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

MySQL配置(com.example.multidb.mysql.config.MySQLConfig)

package com.example.multidb.mysql.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories(
    basePackages = "com.example.multidb.mysql.repository",
    entityManagerFactoryRef = "mysqlEntityManagerFactory",
    transactionManagerRef = "mysqlTransactionManager"
)
@EntityScan("com.example.multidb.mysql.entity")
public class MySQLConfig {

    @Autowired
    private EntityManagerFactoryBuilder builder;

    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "mysqlEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(
            @Qualifier("mysqlDataSource") DataSource dataSource) {
        return builder
                .dataSource(dataSource)
                .packages("com.example.multidb.mysql.entity")
                .persistenceUnit("mysql")
                .build();
    }

    @Bean(name = "mysqlTransactionManager")
    public PlatformTransactionManager mysqlTransactionManager(
            @Qualifier("mysqlEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

MongoDB配置(com.example.multidb.mongodb.config.MongoConfig)

package com.example.multidb.mongodb.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(
    basePackages = "com.example.multidb.mongodb.repository",
    mongoTemplateRef = "mongoTemplate"
)
public class MongoConfig {
    // 默认配置已满足需求,如需自定义可在此扩展
}

实体类与文档类

PostgreSQL实体类

package com.example.multidb.postgres.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "postgres_entities")
public class PostgresEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    
    // getter、setter方法
}

MySQL实体类

package com.example.multidb.mysql.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "mysql_entities")
public class MySQLEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String description;
    
    // getter、setter方法
}

MongoDB文档类

package com.example.multidb.mongodb.document;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "mongodb_documents")
public class MongoDocument {

    @Id
    private String id;

    private String title;
    
    // getter、setter方法
}

仓库接口

PostgreSQL仓库

package com.example.multidb.postgres.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.multidb.postgres.entity.PostgresEntity;

@Repository
public interface PostgresEntityRepository extends JpaRepository<PostgresEntity, Long> {
    // 自定义查询方法可在此添加
}

MySQL仓库

package com.example.multidb.mysql.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.multidb.mysql.entity.MySQLEntity;

@Repository
public interface MySQLEntityRepository extends JpaRepository<MySQLEntity, Long> {
    // 自定义查询方法可在此添加
}

MongoDB仓库

package com.example.multidb.mongodb.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.example.multidb.mongodb.document.MongoDocument;

@Repository
public interface MongoDocumentRepository extends MongoRepository<MongoDocument, String> {
    // 自定义查询方法可在此添加
}

错误修复说明

针对找不到EntityManagerFactoryBuilder bean的错误,修复点如下:

  1. 在MySQL和PostgreSQL的配置类中,通过@Autowired显式注入EntityManagerFactoryBuilder,确保Spring能正确找到该自动配置的bean
  2. 补充导入了缺失的ConfigurationProperties和DataSourceBuilder相关类,避免配置加载失败
  3. 移除了方法参数中的EntityManagerFactoryBuilder注入,改为类成员变量注入,确保注入逻辑稳定

另外,需确保application.yml/application.properties中配置了正确的多数据源信息,示例:

spring:
  datasource:
    mysql:
      url: jdbc:mysql://localhost:3306/mydb_mysql
      username: root
      password: password
      driver-class-name: com.mysql.cj.jdbc.Driver
    postgres:
      url: jdbc:postgresql://localhost:5432/mydb_postgres
      username: postgres
      password: password
      driver-class-name: org.postgresql.Driver
  data:
    mongodb:
      uri: mongodb://localhost:27017/mydb_mongo

内容的提问来源于stack exchange,提问作者SHIVAM SINGH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 05:17:04