当前位置: 首页 > 知识库问答 >
问题:

在Spring引导中连接到多个数据库

孟沛
2023-03-14

我需要连接到我的项目中的两个数据库。所以我创建了两个配置文件。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories( basePackages = {"com.virat.webservices.datastore.v1.Repo" } )
@EntityScan("com.virat.webservices.datastore.v1.Model")
public class V1DBConfig {

@Primary
@Bean( name = "dataSource" )
@ConfigurationProperties( prefix = "v1.datasource" )
public DataSource dataSource()
{
    return DataSourceBuilder.create().build();
}

@Primary
@Bean( name = "entityManagerFactory" )
public LocalContainerEntityManagerFactoryBean entityManagerFactory( EntityManagerFactoryBuilder builder,
        @Qualifier( "dataSource" ) DataSource dataSource )
{
    return builder.dataSource(dataSource).packages("com.virat.webservices.datastore.v1.Model")
            .persistenceUnit("db1").build();
}

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

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories( entityManagerFactoryRef = "v2EntityManagerFactory", transactionManagerRef = "v2TransactionManager",    basePackages = {
    "com.virat.datastore.repository" } )
@EntityScan( "com.virat.datastore.model" )
public class V2DBConfig {

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

@Bean( name = "v2EntityManagerFactory" )
public LocalContainerEntityManagerFactoryBean barEntityManagerFactory( EntityManagerFactoryBuilder builder,
        @Qualifier( "v2DataSource" ) DataSource dataSource )
{
    return builder.dataSource(dataSource).packages("com.virat.model")
            .persistenceUnit("db2").build();
}

@Bean( name = "v2TransactionManager" )
public PlatformTransactionManager barTransactionManager(
        @Qualifier( "v2EntityManagerFactory" ) EntityManagerFactory barEntityManagerFactory )
{
    return new JpaTransactionManager(barEntityManagerFactory);
}
}

我配置了我的应用程序。属性文件格式,

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db2?      useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=fal.   se&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=
#spring.datasource.pool.size=20
v1.datasource.driver-class-name=com.mysql.jdbc.Driver
v1.datasource.url=jdbc:mysql://localhost:3306/db1?     useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=fal.   se&serverTimezone=UTC&useSSL=false
v1.datasource.username=root
v1.datasource.password=
#v1.datasource.pool.size=20
spring.jpa.properties.hibernate.id.new_generator_mappings=false
v1.jpa.properties.hibernate.id.new_generator_mappings=false
#spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

但是当我运行应用程序时,抛出了以下异常。

***************************
APPLICATION FAILED TO START
***************************

Description:

Field entityManager in com.highpeak.tlp.webservices.services.impl.TaskServiceImpl required a single bean, but 2 were found:
    - org.springframework.orm.jpa.SharedEntityManagerCreator#0: defined by method 'createSharedEntityManager' in null
    - org.springframework.orm.jpa.SharedEntityManagerCreator#1: defined by method 'createSharedEntityManager' in null


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

 org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter:42 - 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field entityManager in com.highpeak.tlp.webservices.services.impl.TaskServiceImpl required a single bean, but 2 were found:
    - org.springframework.orm.jpa.SharedEntityManagerCreator#0: defined by method 'createSharedEntityManager' in null
    - org.springframework.orm.jpa.SharedEntityManagerCreator#1: defined by method 'createSharedEntityManager' in null


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

Disconnected from the target VM, address: '127.0.0.1:56875', transport: 'socket'

Process finished with exit code 1

我无法确定错误是什么。我有两个模块。一个数据库的存储实体类位于一个模块中,另一个数据库的类位于另一个模块中。这是问题的根源吗?

编辑

我的TaskServiceImpl。java

package com.virat.webservices.services.impl;


@Service
public class TaskServiceImpl implements TaskService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class);

    @Autowired
    @PersistenceContext(unitName = "v2EntityManagerFactory")
    private EntityManager entityManager;

    @Value( "${file.base.path}" )
    private String basePath;

    @Value( "${application.domain}" )
    private String applicationDomain;

    @Value( "${application.protocol}" )
    private String applicationProtocol;

    @Value( "${server.port}" )
    private String serverPort;

    @Override
    @SuppressWarnings( "unchecked" )
    @Transactional( rollbackOn = DataException.class )
    public Integer doSomething( SomeObject someObject,
            UserAccessDetails userAccessDetails ) throws DataException
    {
        try
        {
            // Do input validations
            if( NullEmptyUtils.isNull(userAccessDetails) || NullEmptyUtils.isNull(someObject) )
            {

                throw new DataException(GeneralConstants.EXCEPTION, GeneralConstants.NULL_INPUT_ERROR,
                        HttpStatus.BAD_REQUEST);
            }

            // Creates a native mysql query based on the contents of lawyerDiscoveryParamsBean
            /* Should be replaced with criteria API */
            String generatedQuery = DynamicQueryGenerator.getDynamicQuery(someObject, owner);
            LOGGER.info("Generated query: {}", generatedQuery);
            Query executableQuery = entityManager.createNativeQuery(generatedQuery, UserModel.class);

            List<UserModel> userModels = executableQuery.getResultList();

            if( userModels.isEmpty() )
            {

                return 0;
            }

            return 1;

        }
        catch( DataException e )
        {
            LOGGER.error(GeneralConstants.ERROR, e);
            throw e;
        }
        catch( Exception e )
        {
            LOGGER.error(GeneralConstants.ERROR, e);
            throw new DataException(GeneralConstants.EXCEPTION, GeneralConstants.SOMETHING_WENT_WRONG,
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}

共有2个答案

怀德馨
2023-03-14

V1DBConfig.java中,注释@EnableJpaRepository实际上应该是这样的,

@EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager", basePackages = {
        "com.virat.webservices.datastore.v1.Repo" } )

您已经在类V2DBConfig中正确地完成了配置。java(查看@EnableJpaRepository注释)。在V1DBConfig中执行相同的操作。java

然后,在TaskServiceImpl中。java,提供PersistenceContext,由@Dan回答。我希望这有帮助。

傅胡媚
2023-03-14

在您的TaskServiceImpl中,确保您正确注释了持久性上下文。

例如:

@PersistenceContext(unitName = "entityManagerFactory")
private EntityManager em;
 类似资料:
  • 问题内容: 我正在使用最新的spring-data- mongodb(1.1.0.M2)和最新的Mongo驱动程序(2.9.0-RC1)。我遇到这样的情况,我有多个客户端连接到我的应用程序,并且我想在同一台Mongo服务器中为每个客户端提供自己的“模式/数据库”。如果我直接使用驱动程序,这并不是一件很难的事情: 看,容易。但是spring-data- mongodb不允许使用简单的方法来使用多个数

  • 问题内容: 我是hibernate和尝试事物的新手。似乎所有令人感兴趣的一件事是如何连接到不同的数据库?我在这里有两个问题: 如果在同一个Web应用程序中,我需要连接到MySQL和Oracle,该怎么办? 我正在使用MySQL,并且有两个数据库test1和test2,如何连接和检索数据? 我在博客中读到我们可以创建不同的配置文件并执行此操作。我尝试过,但是没有成功。这是我尝试过的: 其中path是

  • 我有一个使用Spring引导的Spring批处理作业,它有2个数据源。每个数据源也有2个架构。我需要为这两个数据源指定默认模式。我知道属性spring.jpa.properties.hibernate.default_schema我使用它来指定一个数据源的默认模式。有没有办法为另一个模式指定默认模式? 目前,要为其他数据源指定默认模式,我使用更改会话查询来根据需要切换模式。我试图摆脱这个改变会话查

  • 在我的spring boot应用程序中,我使用Oracle作为数据库。数据库具有不同的模式。我有一个要求,列出所有模式,并在循环中使用该模式连接到数据库,并对表执行一些查询。我看到一些博客通过在应用程序中定义数据源来连接到不同的模式。财产。我不想这样做,因为我已经定义了大约40个模式,我不想定义那么多的数据源。

  • 从bugu-mongo 2.11版本开始,支持连接到多个数据库。 在前面的示例代码中,我们都只是连接到一个数据库: //默认的数据库连接 BuguConnection conn = BuguFramework.getInstance().createConnection(); conn.setHost("192.168.0.100"); conn.setPort(27017); conn.setU

  • 我使用spring boot data redis连接到redis群集,使用版本2.1.3,配置如下: 但是,在操作过程中,始终会收到警告异常消息,如下所示: 这似乎是莴苣的问题,如何映射远程主机