首页 > 解决方案 > 使用 JPA 休眠以在其他模式中生成实体

问题描述

我在我的 JAVA 代码中创建了两个实体,一个是 Account 实体,另一个是 AccountLog 实体。这两个实体映射到名为 testdb 的同一模式中的相应表。我们使用 hibernate 和 JPA 来处理插入/更新和表生成。

由于性能问题,我想将 AccountLog 分离到名为 testdb_log 的其他模式中。这样AccountLog 表将在模式testdb_log 中生成,并且下一个插入/更新事件将存储在模式testdb_log 中。

处理上述情况的最佳解决方案是什么?使用模式名称添加@table 注释?还是其他人?

  1. 如何将实体生成到其他模式?
  2. 对于这个实体,如何将这个实体信息保存/更新到其他模式?

标签: javahibernatejpa

解决方案


我可能会在持久性 xml 中使用不同的持久性单元,如下所示:

<persistence version="2.1"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://xmlns.jcp.org/xml/ns/persistence
        http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

    <persistence-unit name="oneschema" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <properties>
            <property name="driverClass" value="${db.driver}" />
            <property name="jdbcUrl" value="${datasource.baseurl}/SCHEMAONE" />
            <property name="user" value="${datasource.username}" />
            <property name="password" value="${datasource.password}" />
        </properties>
    </persistence-unit>
    <persistence-unit name="anotherchema" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>com.company.AccountLog</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="driverClass" value="${db.driver}" />
            <property name="jdbcUrl" value="${datasource.baseurl}/SCHEMANOTHER" />
            <property name="user" value="${datasource.username}" />
            <property name="password" value="${datasource.password}" />
        </properties>
    </persistence-unit>
</persistence>

在第二个持久性单元中,您明确声明属于它的类,因此实体管理器将知道如何处理它们。

模式、连接、连接池通常对 java 代码是透明的,因此您不应更改 java 中的任何内容。


推荐阅读