【发布时间】:2016-05-16 06:45:23
【问题描述】:
我在 Spring MVC 中遇到“使用多个数据库”的问题 - hibernate JPA
我有两个名为 user_db 和 portal_db 的数据库。我需要在不同的 jpa 单位与他们合作。
这是我的 persistance.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="user_unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Package.Entity1</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/user_db" />
<property name="hibernate.connection.useUnicode" value="true" />
<property name="hibernate.connection.characterEncoding" value="UTF-8" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.connection.username" value="postgres" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />
<!--<property name="hibernate.hbm2ddl.auto" value="create-drop" />-->
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
<persistence-unit name="portal_unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Package.Entity2</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/portal_db" />
<property name="hibernate.connection.useUnicode" value="true" />
<property name="hibernate.connection.characterEncoding" value="UTF-8" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.connection.username" value="postgres" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />
<!--<property name="hibernate.hbm2ddl.auto" value="create-drop"/>-->
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
问题是当我使用 create-drop 并运行我的项目时,它会在两个数据库中创建我的两个实体。应该只能由Package.Entity1在user_unit中创建的表,也在portal_unit中创建。
当我选择、插入、更新我的实体时,我会在每个单独的 DAO 中设置持久性单元。
例如,在 Entity Dao 的实现中,我有:
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
其中 persistenceUnit 可以是 user_unit 或 portal_unit,具体取决于实现。
我应该进行哪些更改以使其不会在两个数据库中创建相同的表?
【问题讨论】:
标签: java spring hibernate spring-mvc jpa