spring jpa hibernate with more datasources

自闭症网瘾萝莉.ら 提交于 2019-12-01 09:19:56
Zaw Than oo

If you would like to use multiple DataSource in Spring + JPA.

  1. Create two or more PersistenceUnit in persistence.xml.
  2. Create EntityManagerFactory for each PersistenceUnit in spring-beans.xml.

More Reference.

  1. Multiple database with Spring+Hibernate+JPA
  2. Access Multiple Database Using Spring 3, Hibernate 3
  3. Multiple Database using Spring 3.0 and Hibernate 3.0

In your DAO classes.

@PersistenceContext(unitName ="JPA_1")
private EntityManager em_1; 

@PersistenceContext(unitName ="JPA_2")
private EntityManager em_2; 

Conig persistence.xml

<persistence-unit name="JPA_1" type="RESOURCE_LOCAL">
....
</persistence-unit>


<persistence-unit name="JPA_2" type="RESOURCE_LOCAL">
....
</persistence-unit>

Config : spring-beans.xml

<bean id="entityManagerFactory1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="JPA_1"/>
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect"/> <--if it is necessary, replace with hibernate.
    </property>
    <property name="jpaPropertyMap">
        <props>
            <prop key="eclipselink.weaving">false</prop> <--if it is necessary, replace with hibernate.
        </props>
    </property>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver">
        </bean>
    </property>
</bean>

<bean id="entityManagerFactory2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="JPA_2"/>
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect"/> <--if it is necessary, replace with hibernate.
    </property>
    <property name="jpaPropertyMap">
        <props>
            <prop key="eclipselink.weaving">false</prop> <--if it is necessary, replace with hibernate.
        </props>
    </property>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver">
        </bean>
    </property>
</bean> 

<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"> <--if it is necessary, replace with hibernate.
    <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform"/>
    <!--<property name="databasePlatform" value="org.eclipse.persistence.platform.database.OraclePlatform" />-->
    <property name="generateDdl" value="false"/>
    <property name="showSql" value="true"/>
</bean>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!