【问题标题】:How do you represent collections of Hibernate objects in a single POJO?如何在单个 POJO 中表示 Hibernate 对象的集合?
【发布时间】:2011-11-02 07:57:46
【问题描述】:

考虑以下 Hibernate 映射:

<hibernate-mapping package="org.example">
  <class name="Customer" table="CUSTOMER">
    <id name="customerId" column="customer_id"/>

    <bag name="itineraries" table="ITINERARY" inverse="true" cascade="all">
      <key column="customer_id"/>
      <one-to-many class="Itinerary"/>
    </bag>

    <bag name="hotels" table="HOTEL" inverse="true" cascade="all">
      <key column="customer_id"/>
      <one-to-many class="Hotel"/>
    </bag>
  </class>
</hibernate-mapping>

<hibernate-mapping package="org.example">
    <class name="Itinerary" table="ITINERARY">
      <many-to-one name="customer" column="customer_id" update="false" not-null="true"/>
      ...other properties...
    </class>
</hibernate-mapping>

<hibernate-mapping package="org.example">
    <class name="Hotel" table="HOTEL">
      <many-to-one name="customer" column="customer_id" update="false" not-null="true"/>
      ...other properties...
    </class>
</hibernate-mapping>

现在假设您需要删除 CUSTOMER 表。您将如何重构映射/模型,以使 Customer Java 对象继续包含基于 customerId 的 Itinerary 和 Hotel 对象列表?上述 Hotel 和 Itinerary 对象仍然需要由 Hibernate 管理。

我能想到的最好的方法是在调用者请求列表时将 Customer 对象推迟到 DAO。是否有更简洁的方法仍然允许 Customer 对象存在于每个 Itinerary 和 Hotel 对象中?

【问题讨论】:

  • 为什么要删除 CUSTOMER 表?
  • 这确实是假设,但假设 CUSTOMER 表正在移动到其他无法访问的模式。

标签: java hibernate dao hibernate-mapping


【解决方案1】:

一旦您删除客户表,客户对象将不再由 Hibernate 管理。如果您仍然想要一个包含 Itinerary 和 Hotel 的客户对象,则需要以编程方式完成。我不确定你是否真的在寻找这个。

一种可能的方法是

  1. 假设您有一个带有getCustomer() 方法的DAO。这接受客户 ID。
  2. 此方法会触发另外两个查询,以根据客户 ID 获取行程和酒店列表。
  3. 它创建一个客户对象并将行程和酒店列表设置到其中并返回它和填充的客户对象。

【讨论】:

  • 谢谢,桑托什。是的,这与我现在所拥有的很接近: 1. 有人调用 getCustomer(customerId)。一个新的客户对象与一个 customerId 成员变量一起返回。 2. 有人调用customer.getItineraries()。客户对象只是根据 itineraryDao 来检索当前客户的行程。理想的做法是将行程和酒店映射到 Customer 对象的多个休眠映射,但我不确定 Hibernate 是否可以这样工作......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
  • 2017-09-02
  • 2015-01-01
  • 1970-01-01
相关资源
最近更新 更多