在两个不同的数据库中插入两个表

时间:2014-03-21 08:43:07

标签: java spring hibernate jpa

我在Spring框架上的Java Web应用程序使用两个数据库,例如database-1和database-2。两个数据库都有User表。我想要做的是同时在两个表中插入记录。

persistence-unit中有两个persistence.xml指向数据库。

这是我的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="p1-jpa" transaction-type="RESOURCE_LOCAL">

        <provider>org.hibernate.ejb.HibernatePersistence</provider>


         <jta-data-source>java:jboss/datasources/MySqlDS2</jta-data-source> 

        <class>com.xyz.entity.User</class>
        <exclude-unlisted-classes />

        <properties>
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
        </properties>

    </persistence-unit>

    <persistence-unit name="p2-jpa" transaction-type="RESOURCE_LOCAL">

        <provider>org.hibernate.ejb.HibernatePersistence</provider>


         <jta-data-source>java:jboss/datasources/MySqlDS2</jta-data-source>         
         <class>com.mmxhealthcare.entity.MMASCUser</class>  
         <exclude-unlisted-classes />

        <properties>
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
        </properties>

    </persistence-unit>
    </persistence>

现在每当我尝试添加用户时,它都只插入Database-1。我没有任何例外。

这是我的spring-servlet.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:jaxrs="http://cxf.apache.org/jaxrs"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:security="http://www.springframework.org/schema/security"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-3.1.xsd 
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
        <property name="order" value="0"/>
    </bean>

    <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> -->
    <context:property-placeholder location="classpath:config.properties" />
    <context:annotation-config />

    <context:component-scan base-package="com.xyz.controller" />
    <context:component-scan base-package="com.xyz.service" />
    <context:component-scan base-package="com.xyz.dao" />
    <context:component-scan base-package="com.xyz.security" />
    <context:component-scan base-package="com.xyz.dto" />
    <context:component-scan base-package="com.xyz.util" />
    <context:component-scan base-package="com.xyz.entity" />

    <tx:annotation-driven />

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

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

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

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


    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="d1SourceLocal" />
        <property name="persistenceUnitName" value="p1-jpa" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
    </bean>

    <bean id="mmascentityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="d2DataSourceLocal" />
        <property name="persistenceUnitName" value="p2-jpa" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
    </bean>

    <!-- <bean id="dataSourceLocal" class="org.springframework.jndi.JndiObjectFactoryBean">  
        <property name="jndiName" value="java:jboss/datasources/MySqlDS2"/>  
    </bean> -->

    <!-- Local -->
    <bean id="d1SourceLocal"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.username}" />
        <property name="password" value="${database.password}" />
    </bean>


    <bean id="d2DataSourceLocal"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${d2-database.driver}" />
        <property name="url" value="${d2-database.url}" />
        <property name="username" value="${d2-database.username}" />
        <property name="password" value="${d2-database.password}" />
    </bean>
</beans>

这是我的service课程:

public class Userservice{
    @Autowired
    Database2IUserDAO immDao;

    @Autowired 
    Database1IUserDAO iaaDao;

    public User saveUser(fname,address){
    User u  = new User(); // This points Database-1 User table.
    u.setFname(fname);
    u.setAddress(address);
    iaaDao.save(u);
    User2 u2 = new User2(); // This points Database-2 User table.
    u2.setFname(fname);
    u2.setAddress(address);
    immDao.save(u2);
    }
}

这是我的Database1IUserDAO //这是一个界面

  package com.xyz.dao;
    public interface Database1IUserDAO {

        public Object save(Object ob);

    }

这是我的Database2IUserDAO //这是database2的另一个接口

package com.xyz.dao;
public interface Database2IUserDAO {

    public Object save(Object ob);

}

**这最终是Database-1和Database 2的DAO类** 我的两个DAO类都扩展了BaseDao类,它有我们用来插入或保存的Save()方法。

BaseDao.java

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;


public class BaseDAO {

    protected EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this. entityManager = entityManager;
    }

    @Transactional
    public Object save(Object ob) {
        Object object = entityManager.merge(ob);
        return object;
    }

    @Transactional
    public void remove(Object ob) {
        Object object = entityManager.merge(ob);
        entityManager.remove(object);
    }

    @Transactional
    public int update(String query) {
        return entityManager.createQuery(query).executeUpdate();
    }

}

请帮忙。

3 个答案:

答案 0 :(得分:3)

您必须使用Transaction Manager文件中提到的数据库特定spring-context.xml,如下所示。

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

您应该在DAO Class中使用特定于数据库的Transaction Manager创建保存功能,如下所示:

@Transactional(value="transactionManager2")
public Object save(Object ob) {
     Object object = entityManager.merge(ob);
     return object;
}

我希望它对你有用。

答案 1 :(得分:1)

您似乎使用BaseDAO中的所有DAO使用相同的EntityManager(EM)。由于您没有指定EM正在使用哪个TransactionManager,因此默认为这个:

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

...如文档http://docs.spring.io/spring/docs/2.0.8/reference/transaction.html中所述(查找表9.2)

table 9.2

如果要写入另一个数据库,则需要明确告诉Spring您要使用哪个数据库。以这个答案为例:

Spring multiple @Transactional datasources

答案 2 :(得分:0)

看起来你对持久性单元使用相同的数据源。

即java:jboss / datasources / MySqlDS2

所以它只插入一个与上述数据源mstly Mysql DB对应的DB。

所以在持久性单元中添加不同的数据源,这应该可以帮助您插入两个数据库。

它不会给出任何异常,因为您使用的一个数据源可能是有效的数据源(我无法保证,因为我们在您的帖子中没有数据源信息)。

让我知道其他任何事情。