如何在 Spring Boot 项目中配置多个数据库(PostgreSQL、MongoDB 和 MySQL)?

问题描述 投票:0回答:1

项目结构

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 Driver -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.6.0</version>
    </dependency>

    <!-- MySQL Driver -->
    <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>

    <!-- Other necessary dependencies -->
    <!-- ... -->
</dependencies>

设置配置类

为每个关系数据库(PostgreSQL 和 MySQL)和 MongoDB 设置单独的配置类。

PostgreSQL 配置

在 com.example.multidb.postgres.config 中为 PostgreSQL 创建一个配置类。 包 com.example.multidb.postgres.config;


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

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
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 {

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

    @Bean(name = "postgresEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean postgresEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @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 中创建 MySQL 的配置类。


package com.example.multidb.mysql.config;

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

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
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 {

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

    @Bean(name = "mysqlEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @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 配置

对于 MongoDB,Spring Data MongoDB 提供自动配置。但是,如果您需要自定义配置,则可以定义它们。在 com.example.multidb.mongodb.config 中创建一个配置类。

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 {
    // Default configurations are usually sufficient.
    // Customize if necessary.
}

定义实体和文档类

为 PostgreSQL 和 MySQL 创建实体类,为 MongoDB 创建文档类。

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;
    // Other fields, getters, setters
}

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;
    // Other fields, getters, setters
}

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;
    // Other fields, getters, setters
}

创建存储库接口

为各自包中的每种数据库类型定义存储库接口。

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> {
    // Define query methods if needed
}

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> {
    // Define query methods if needed
}

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> {
    // Define query methods if needed
}

错误

考虑在配置中定义“org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder”类型的 bean。

描述:

com.example.multidb.mysql.config.MySQLConfig 中方法 mysqlEntityManagerFactory 的参数 0 需要类型为“org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder”的 bean,但无法找到。

spring-boot jpa
1个回答
0
投票

EntityManagerFactoryBuilder
是由
org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration
提供的 Bean,仅由
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration

启动
@ConditionalOnSingleCandidate(DataSource.class)
class HibernateJpaConfiguration extends JpaBaseConfiguration {

注意

@ConditionalOnSingleCandidate(DataSource.class)
,在你的情况下,它不是真的,因此例外
bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' that could not be found

我看到 2 个选项:

  • 您使用 @Primay 标记您的数据源之一,因为 @ConditionalOnSingleCandidate 规定“如果 BeanFactory 中已包含多个匹配的 bean 实例,但已定义主要候选者,则条件也将匹配;本质上,如果自动装配,则条件匹配”
  • 您使用特定限定符为每个数据源创建构建器的实例(就像您对其余 bean 所做的那样)

然后它应该按预期工作

© www.soinside.com 2019 - 2024. All rights reserved.