使用多个数据源时Spring中存在多个实体管理器问题

时间:2010-09-16 21:36:10

标签: java spring jpa dao

我的applicationContext.xml中有两个实体管理器,对应两个不同的数据库。我可以使用database1轻松查询entityManager1,但当我尝试使用database2访问entityManager2时,我无法获得任何结果。我正在使用Spring + Hibernate + JPA。

这是我的ApplicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>

    <beans default-autowire="byName"
     xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

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


 <bean id="entityManagerFactory"
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="jpaVendorAdapter">
   <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="database" value="INFORMIX" />
    <property name="showSql" value="true" />
   </bean>
  </property>
  <property name="persistenceUnitManager" ref="persistenceUnitManager" />
  <property name="persistenceUnitName" value="PU1" />
 </bean>



 <bean id="entityManagerFactory2"
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="dataSource" ref="dataSource2" />
  <property name="jpaVendorAdapter">
   <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="database" value="INFORMIX" />
    <property name="showSql" value="true" />
   </bean>
  </property>
  <property name="persistenceUnitManager" ref="persistenceUnitManager" />
  <property name="persistenceUnitName" value="PU2" />
 </bean>



 <!-- Data Sources -->

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
  <property name="url"
   value="jdbc:db2://HOST_NAME:PORT_NO/DB_NAME:INFORMIXSERVER=SERVER_NAME;DELIMIDENT=y;" />
  <property name="username" value="username" />
  <property name="password" value="password" />
  <property name="minIdle" value="2" />
 </bean>

 <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
  <property name="url"
   value="jdbc:db2://HOST_NAME:PORT_NO/DB_NAME2:INFORMIXSERVER=SERVER_NAME;DELIMIDENT=y;" />
  <property name="username" value="username" />
  <property name="password" value="password" />
  <property name="minIdle" value="2" />
 </bean>

 <bean
  class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
  lazy-init="false">
  <property name="targetObject" ref="dataSource" />
  <property name="targetMethod" value="addConnectionProperty" />
  <property name="arguments">
   <list>
    <value>characterEncoding</value>
    <value>UTF-8</value>
   </list>
  </property>
 </bean>

 <bean
  class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
  lazy-init="false">
  <property name="targetObject" ref="dataSource2" />
  <property name="targetMethod" value="addConnectionProperty" />
  <property name="arguments">
   <list>
    <value>characterEncoding</value>
    <value>UTF-8</value>
   </list>
  </property>
 </bean>

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
  scope="prototype">
  <property name="dataSource" ref="dataSource" />
 </bean>



 <bean id="persistenceUnitManager"
  class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
  <property name="persistenceXmlLocations">
   <list>
    <value>classpath*:META-INF/persistence.xml</value>
    <value>classpath*:META-INF/persistence2.xml</value>
   </list>
  </property>
  <property name="dataSources">
   <map>
    <entry key="localDataSource" value-ref="dataSource" />
    <entry key="dataSource2" value-ref="dataSource2" />
   </map>
  </property>
  <property name="defaultDataSource" ref="dataSource" />
 </bean>



 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory" />
 </bean>

 <bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory2" />
 </bean>

 <tx:annotation-driven transaction-manager="transactionManager" />
 <tx:annotation-driven transaction-manager="transactionManager2" />

 <!-- MORE Action and DAO beans -->


</beans>

这是我的服务层代码,适用于enityManager1

  @Transactional
    public class StatesDAO implements IStatesDAO {
 private EntityManager em;

 @PersistenceContext(unitName = "PU1")
 public void setEntityManager(EntityManager em) {
  this.em = em;
 }

 private EntityManager getEntityManager() {
  return em;
 }

 @SuppressWarnings("unchecked")
 public List<States> findAll() {
  logger.info("finding all States instances");
  try {
   final String queryString = "select model from States model";

   Query query = getEntityManager().createQuery(queryString);
   return query.getResultList();

  } catch (RuntimeException re) {
   throw re;
  }

 }

    }

我的两个persitence.xml文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
 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">
 <persistence-unit name="PU1" transaction-type="RESOURCE_LOCAL">
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
  <class>com.jpa.entity.States</class>
 </persistence-unit>
</persistence>

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
 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">
 <persistence-unit name="PU2" transaction-type="RESOURCE_LOCAL">
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
  <class>com.jpa.other.entity.States</class>
 </persistence-unit>
</persistence>

如果我更改了我的服务层(如下所示),我没有得到任何结果。基本上,列表的大小为零:

@Transactional
public class StatesDAO implements IStatesDAO {
private EntityManager em;

@PersistenceContext(unitName = "PU2")
public void setEntityManager(EntityManager em) {
    this.em = em;
}

private EntityManager getEntityManager() {
    return em;
}

@SuppressWarnings("unchecked")
public List<com.jpa.other.entity.States> findAll() {
    logger.info("finding all States instances");
    try {
        final String queryString = "select model from States model";

        Query query = getEntityManager().createQuery(queryString);
        return query.getResultList();

    } catch (RuntimeException re) {
        throw re;
    }

}

}

所以基本上你可以看到我有两个具有完全相同结构的实体(状态),为了区分彼此,我将它们放入单独的包中

根据我的知识,我在这里没有做任何疯狂的事情,但它似乎仍然无法正常工作。这个问题是怎么造成的,如何解决?

后续行动:我忘记提及的一件事是即使有两个不同的数据库,但数据库服务器名称相同。我不知道这是否是一个有用的信息。所以想到分享它。

这是我现在得到的例外:

16:24:44,732 INFO [STDOUT] Hibernate: select state0_.state as col_0_0_ from states state0_ 
16:24:44,753 WARN [JDBCExceptionReporter] SQL Warning: 36106, SQLState: 01I01 
16:24:44,753 WARN [JDBCExceptionReporter] IDS SQL Warning: SQLCODE=36106, SQLSTATE=01I01, SQLERRMC=0;819;informix;;IDS/NT32;1;1;0;819;0;, DRIVER=4.7.85 

1 个答案:

答案 0 :(得分:11)

我遇到了同样的问题,但是有多个Hibernate会话工厂:2个具有相同结构的DB,我不想拥有2个相同的DAO集等等。虽然我的体验是Hibernate,但我怀疑你可以使用相同的解决方案:Spring AbstractRoutingDataSource。它允许您配置应用程序,以根据ThreadLocal上设置的值在运行时确定要使用的数据源。有关简介,请参阅http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/。最终发生的事情是,工厂中的dataSource引用不会指向硬编码的dataSource bean,而是指向AbstractRoutingDataSource。要设置每个线程的切换,请使用@Aspect确定要命中的数据库。