简体   繁体   中英

How do you represent collections of Hibernate objects in a single POJO?

Consider the following Hibernate mappings:

<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>

Now say you need to remove the CUSTOMER table. How would you refactor the mappings/model such that the Customer Java object continues to contain Lists of Itinerary and Hotel objects based on a customerId? Said Hotel and Itinerary objects still need to be managed by Hibernate.

The best I can come up with is the Customer object deferring to DAOs when callers request a List. Is there a cleaner approach that will still allow the Customer object to live in each Itinerary and Hotel object?

Once you remove the customer table, the customer object will not be managed by Hibernate anymore. If you still want to have a customer object containing Itinerary and Hotel, then that needs to be done programmatically. I am not sure if you are really looking for this.

One possible way of doing this is

  1. Lets say you have a DAO with a method getCustomer(). This accepts a customer id.
  2. This method fires two more queries to fetch lists of Itinerary and Hotel based on the customer id.
  3. It creates a Customer object and sets the lists of Itinerary and Hotel into it and returns it and populated customer object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM