Spring+jpa连接多个数据库

1.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="DBNAME1"
    	transaction-type="RESOURCE_LOCAL">
    <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
	    <class>cn.wiztek.hprms.domain.Building</class>
		<class>cn.db.domain.tablename1</class>
    <properties>
        <property name="openjpa.Log" value="log4j"/>
    </properties>
  </persistence-unit>
   <persistence-unit name="DBNAME2"
    	transaction-type="RESOURCE_LOCAL">
    <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
	    <class>cn.db2.domain.tablename1</class>
    <properties>
        <property name="openjpa.Log" value="log4j"/>
    </properties>
  </persistence-unit>
</persistence>

2.ApplicationContext.xml(写了两个。。还有个ApplicationContext1.xml内容差不多)

<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://127.0.0.1:50000/testdb" />
		<property name="username" value="username" />
		<property name="password" value="pwd" />
	</bean>

	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="DBNAME1" />
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="jpaVendorAdapter">
			<bean
				class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
			</bean>
		</property>
	</bean>

两个文件里面唯一不同的就是dataSource分别连接两个数据库,persistenceUnitName分别为DBNAME1和DBNAME2。

3.BeansFactory.java(还是两个,ClassPathResource分别写的ApplicationContext.xml和ApplicationContext1.xml)

public class BeansFactory {
	private static Resource res = null;//new ClassPathResource("/cn/wiztek/remis/config/service.xml");//new ClassPathResource("/cn/wiztek/remis/config/service.xml");
	private static BeanFactory factory = null;//new XmlBeanFactory(res);//new XmlBeanFactory(res);
	static {
		try {
			System.out.println("!!!");
			res = new ClassPathResource("ApplicationContext.xml");
			factory = new XmlBeanFactory(res);
		} catch (Throwable ex) {
			System.err.println(ex);
			ex.printStackTrace();
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static Object getBean(String beanName){
		return factory.getBean(beanName);
	}
}

相关推荐