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); } }
相关推荐
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
XGQ 2020-07-04
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16
wcqwcq 2020-06-14
yuanye0 2020-06-14
zhongliwen 2020-06-13
MrFuWen 2020-06-09