当前位置: 首页 > 面试题库 >

使用Spring + Hibernate + JPA的多个数据库

胡曾笑
2023-03-14
问题内容

我正在尝试配置Spring + Hibernate + JPA以使用两个数据库(MySQL和MSSQL)。

我的datasource-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"
 xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:util="http://www.springframework.org/schema/util">

 <!--
 Data Source config 
  -->
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}"
  p:username="${local.jdbc.username}" p:password="${local.jdbc.password}">
 </bean>

 <bean id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close" p:driverClassName="${remote.jdbc.driver}"
  p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}"
  p:password="${remote.jdbc.password}" />

 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
  p:entity-manager-factory-ref="entityManagerFactory" />

 <!-- 
    JPA config   
    -->
 <tx:annotation-driven transaction-manager="transactionManager" />

 <bean id="persistenceUnitManager"
  class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
        <property name="persistenceXmlLocations">
   <list value-type="java.lang.String">
    <value>classpath*:config/persistence.local.xml</value>
    <value>classpath*:config/persistence.remote.xml</value>
   </list>
  </property>

  <property name="dataSources">
   <map>
    <entry key="localDataSource" value-ref="dataSource" />
    <entry key="remoteDataSource" value-ref="dataSourceRemote" />
   </map>
  </property>
  <property name="defaultDataSource" ref="dataSource" />
 </bean>

 <bean id="entityManagerFactory"
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="jpaVendorAdapter">
   <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
    p:showSql="true" p:generateDdl="true">
   </bean>
  </property>
  <property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="localjpa"/>
 </bean>

 <bean
  class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

</beans>

每个persistence.xml包含一个单元,如下所示:

<persistence-unit name="remote" transaction-type="RESOURCE_LOCAL">
  <properties>
   <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" />
   <property name="hibernate.dialect" value="${remote.hibernate.dialect}" />
   <property name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" />
  </properties>
 </persistence-unit>

PersistenceUnitManager导致以下异常:

Cannot resolve reference to bean 'persistenceUnitManager' while setting bean property 'persistenceUnitManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceUnitManager' defined in class path resource [config/datasource-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.util.ArrayList] to required type [java.lang.String] for property 'persistenceXmlLocation'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.util.ArrayList] to required type [java.lang.String] for property 'persistenceXmlLocation': no matching editors or conversion strategy found

如果只留下一个没有列表的persistence.xml,则每个列表都可以正常工作,但我需要2个单元…

我还尝试在Spring + Hibernate上下文中找到用于两个数据库的替代解决方案,因此,我将不胜感激。

更改为以后的新错误persistenceXmlLocations:

{classpath:config / persistence.local.xml,classpath:config / persistence.remote.xml}中没有定义任何默认的持久性单元

更新:

我添加了persistenceUnitName,它可以工作,但是只有一个单元仍然需要帮助。

更新:

我更改了配置文件:datasource-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}"
        p:username="${local.jdbc.username}" p:password="${local.jdbc.password}">
    </bean>

    <bean id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${remote.jdbc.driver}"
        p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}"
        p:password="${remote.jdbc.password}">
    </bean>

    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
        <property name="defaultPersistenceUnitName" value="pu1" />
    </bean>

    <bean id="persistenceUnitManager"
        class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
        <property name="persistenceXmlLocation" value="${persistence.xml.location}" />
        <property name="defaultDataSource" ref="dataSource" /> <!-- problem -->
        <property name="dataSources">
            <map>
                <entry key="local" value-ref="dataSource" />
                <entry key="remote" value-ref="dataSourceRemote" />
            </map>
        </property>
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
                p:showSql="true" p:generateDdl="true">
            </bean>
        </property>
        <property name="persistenceUnitManager" ref="persistenceUnitManager" />
        <property name="persistenceUnitName" value="pu1" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="entityManagerFactoryRemote"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
                p:showSql="true" p:generateDdl="true">
            </bean>
        </property>
        <property name="persistenceUnitManager" ref="persistenceUnitManager" />
        <property name="persistenceUnitName" value="pu2" />
        <property name="dataSource" ref="dataSourceRemote" />
    </bean>

    <tx:annotation-driven />

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
        p:entity-manager-factory-ref="entityManagerFactory" />


    <bean id="transactionManagerRemote" class="org.springframework.orm.jpa.JpaTransactionManager"
        p:entity-manager-factory-ref="entityManagerFactoryRemote" />

</beans>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
                 http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="pu1" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" />
            <property name="hibernate.dialect" value="${local.hibernate.dialect}" />
            <property name="hibernate.hbm2ddl.auto" value="${local.hibernate.hbm2ddl.auto}" />                          
        </properties>
    </persistence-unit>

    <persistence-unit name="pu2" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" />
            <property name="hibernate.dialect" value="${remote.hibernate.dialect}" />
            <property name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" />
        </properties>
    </persistence-unit>

</persistence>

现在,它构建了两个entityManagerFactory,但是两者都用于Microsoft SQL Server

[main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [
    name: pu1
    ...]
[main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server

[main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [
    name: pu2
    ...]
[main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server (but must MySQL)

我建议仅使用dataSource,dataSourceRemote(不进行替换)不起作用。那是我的最后一个问题。


问题答案:

你需要使用persistenceXmlLocations属性(请注意复数)而不是persistenceXmlLocation。这是一个字符串数组,因此将自动从list转换:

<bean id="persistenceUnitManager"
      class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
  <property name="persistenceXmlLocations"><list>
    <value>classpath*:config/persistence.local.xml</value>
    <value>classpath*:config/persistence.remote.xml</value>
  </list></property>
  ...

entityManagerFactory未指定persistenceUnitName属性。你必须明确地执行此操作,因为你要定义多个持久性单元,entityManagerFactory并且必须知道要使用哪个持久性单



 类似资料:
  • 问题内容: 我有一个Spring + Hibernate + JPA应用程序。用户登录时,可以从要连接的数据库列表中进行选择(这是要求)。所有数据库都有相同的架构,因此将使用相同的实体和DAO。 现在,我有一个EntityManager(目前正在使用一个数据库),它被注入到DAO中,如下所示: 有什么方法可以让DAO根据从服务层接收到的参数/属性自动接收entityManager(由Spring管

  • 我有相同的数据库模式database_1和database_2,希望对这两个数据库进行配置(database schema相同),并确定使用哪个数据库的运行时<我的坚持。xml如下所示: 持久性名称第二个配置如下: 两个持久性单元加载相同的类。现在我的数据库配置。xml作为配置持久化单元和数据源的地方。如下所示,第一个持久化单元名称配置为,数据源名称为datasource: 现在,此代码用于将第二

  • 问题内容: 有人知道如何在hibernate配置中添加另一个数据源,以及如何在自己的DAO中将Spring配置为其自动注入该数据源吗? 这是我的带有一个数据源的代码,可以完美运行,但是我不知道如何添加另一个数据源。我想添加另一个数据源,该数据源是具有与实际数据库不同的表的数据库。 DAO EXAMPLE 问题答案: 我假定你有一组应使用的DAO的和适当的,而其他人应该使用不同的和基于。当然,你需要

  • 我们的应用程序是一个中间层应用程序,它提供了十几个左右的前端应用程序,可以访问后端的几十个数据库(和其他数据源)。 我们决定使用OSGi将不相关的代码位分离到单独的包中。这确保了正确的代码封装,甚至允许特定捆绑包的热交换。 这样做的一个优点是,与特定数据库对话的任何代码都被隔离到单个捆绑包中。它还允许我们简单地为新的目的地插入新的捆绑包,并无缝地集成新代码。它还确保了如果单个后端数据源关闭,对其他

  • 问题内容: 我有一个需要配置基于Spring的应用程序以与两个数据库一起使用的要求。我们有两个数据库,一个用于保存实时数据,另一个数据库用作数据仓库,并包含存档的数据(其结构与实时数据库完全相同)。 为简单起见,假设存在搜索产品的请求。应用程序应该做的是在实时数据库中搜索产品详细信息,如果找不到,它将检查存档数据库。 如果需要配置这样的设置,是否仍需要配置数据源,搜索代码是否必须使用第一个数据源来

  • 描述:com.cavion.services.UserDataService中得字段userDataRepo需要一个名为“Entity ManagerFactory”得bean,但找不到该bean.操作:考虑在您的配置中定义一个名为'Entity ManagerFactory‘的bean。 我需要在我的JPA存储库上指定entityManagerFactoryRef。 但是我有许多存储库类,其中一