如何在Spring JPA中使用多个数据库设置

时间:2013-09-17 01:02:49

标签: spring jpa datasource spring-data spring-data-jpa

我坚持在Spring JPA中使用两个数据库。错误表示缺少表格:电话。

这是我的设定。

META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">

    <persistence-unit name="default-jpa" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>

    <persistence-unit name="kiews-ecc-jpa" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>

</persistence>


default-jpa-context.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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">

    <!-- Datasource -->
    <bean id="defaultDataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${default.db.driver}" />
        <property name="url" value="${default.db.url}" />
        <property name="username" value="${default.db.username}" />
        <property name="password" value="${default.db.password}" />
    </bean>

    <!-- Entity Manager -->
    <bean id="defaultEntityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="defaultDataSource" />
        <property name="persistenceUnitName" value="default-jpa" />
    </bean>

    <!-- Transaction Manager -->
    <bean id="defaultTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="defaultEntityManagerFactory" />
        <property name="dataSource" ref="defaultDataSource" />
    </bean>

    <tx:annotation-driven transaction-manager="defaultTxManager" proxy-target-class="true"/>

    <jpa:repositories base-package="mypackage.repositories.default" entity-manager-factory-ref="defaultEntityManagerFactory" />
</beans>


ecc-jpa-context.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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">

    <!-- Datasource definition -->
        <bean id="eccDataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${ecc.db.driver}" />
        <property name="url" value="${ecc.db.url}" />
        <property name="username" value="${ecc.db.username}" />
        <property name="password" value="${ecc.db.password}" />
    </bean>

    <!-- EntityManagerFactory -->
    <bean id="eccEntityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="eccDataSource" />
        <property name="persistenceUnitName" value="kiews-ecc-jpa" />
    </bean>

    <!-- TransactionManager -->
    <bean id="eccTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="eccEntityManagerFactory" />
        <!-- <property name="dataSource" ref="eccDataSource" /> -->
    </bean>

    <tx:annotation-driven transaction-manager="eccTxManager" proxy-target-class="true"/>

    <jpa:repositories base-package="mypackage.repositories.ecc" entity-manager-factory-ref="eccEntityManagerFactory" />

</beans>

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
            http://www.springframework.org/schema/data/jpa
            http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!-- ========================= GENERAL DEFINITIONS ========================= -->
    <!-- Scanning beans -->
    <context:component-scan base-package="mypackage.controllers" />

    <!-- Autowired config -->
    <context:annotation-config />

    <!-- @RequestMapping, @Controller, @RequestBody/ResponseBody, @Valid -->
    <mvc:annotation-driven />

    <!-- Configurer that replaces ${...} placeholders with values from properties files -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:myprefs.properties</value>
            </list>
        </property>
    </bean>

    <!-- for JSON, @ResponseBody -->
    <bean id="jacksonMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter" />
            </list>
        </property>
    </bean>

    <!-- Spring JPA Configuration -->
    <import resource="default-jpa-context.xml" />
    <import resource="ecc-jpa-context.xml" />

    <!-- Services -->
    <!-- Services goes here --->

</beans>


Phone.java
@Entity
@Table(name="phones")
public class Phone implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long phoneId;

    @ManyToOne
    @JoinColumn(name="fkplanid", referencedColumnName="planId", insertable=false, updatable=false)
    @JsonIgnore
    @NotFound(action=NotFoundAction.IGNORE)
    private Plan plan;
    private String sim;
    private String imei;
    private String phoneType;
    private String label;

        //Getters and setters
}

@Entity
@Table(name="plans")
public class Plan implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long planId;

    private String planName;

    //Other fields goes here

    @OneToMany(mappedBy="plan", fetch=FetchType.EAGER)
    @NotFound(action=NotFoundAction.IGNORE)
    @JsonIgnore
    private List<Phone> phones;

        //Getters and setters
}

PhoneRepositoryTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class PhoneRepositoryTest {

    @Autowired private PhoneRepository repos;

    @Test
    public void testFindAll(){
        List<Phone> phones = (List<Phone>)repos.findAll();
                assertTrue(!phones.isEmpty());
    }

}

我有不同的实体和存储库包,数据源设置是正确的。我在尝试存储库测试时遇到此错误。

Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default-jpa] Unable to build EntityManagerFactory
Caused by: org.hibernate.HibernateException: Missing table: phones
    at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1262)
    at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:155)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:508)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1750)
    at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:920)

电话表存在于ecc-jpa数据库中,而不是default-jpa数据库,但是default-jpa在加载时也试图查找电话表。

我还需要查看更多内容?您的回答将不胜感激。

1 个答案:

答案 0 :(得分:1)

我找到了原因。问题来自以下设置。

<property name="hibernate.hbm2ddl.auto" value="validate" />

以上使JPA检查实体的架构,我也试图查找电话表。