开发者

Hibernate parent-child mapping

I'm trying to map an order and its order items in Hibernate. An order item should not be able to reference its parent order:

public class Order {
    private long id;
    private Set<OrderIter> orderItems = new HashSet<OrderItem>();

    public long id() {
        return id;
    }

    public void add(OrderItem item) {
        item.setItemNumber(orderItems.size() + 1);
        orderItems.add(item);
    }

    public Set<OrderItem> orderItems() {
        return Sets.newHashSet(orderItems);
    }
}


public class OrderItem {
    private int itemNumber;

    public int itemNumber() {
        return itemNumber;
    }

    public void setItemNumber(int itemNumber) {
        this.itemNumber = itemNumber;
    }
}

The objective is to have Hibernate automatically persist an order item when it's added to an order, like this:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();


Order order = (Order) session.load(Order.class, orderId);
OrderItem item = new OrderItem();
order.add(item);

// Done

session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();

I looked at Chapter 24. Example: Parent/Child, but in this example the child has a reference to the parent. I'm now trying to map it using Collections of dependent objects:

<class name="Order" table="ORDERS">
    <id name="id" column="ORDER_ID" access="field">
        <generator class="native" />
    </id>

    <set name="or开发者_运维知识库ders" table="ORDER_ITEMS" access="field">
        <key column="id" />
        <composite-element class="OrderItem">
            <property name="ItemNumber" access="field" />
        </composite-element>
    </set>
</class>

This is almost working, but the combination of order id and item number should be unique. How can I meet all these criteria with a Hibernate mapping?


Here the one-to-many association between Order->OrderItem is mapped using a JOIN TABLE. The one-to-many association is mapped with a many-to-many with unique set to true. (since one-to-many is not aware of a join table on the set)

   <class name="Order" table="ORDERS">
        <set name="orders" table="ORDER_ORDERITEMS_RT">
            <key column="ORDER_ID" />
            <many-to-many name="OrderItem" unique="true" column="ORDERITEM_ID"/>
        </set>
    </class>

    <class name="OrderItem table="ORDERITEMS">

    </class>

The above mapping satisfies

  1. OrderItem not having a reference to Order. As the mapping are in a separate table
  2. One-to-many association makes the orderid-orderitemid pair unique.
  3. You can put appropriate cascading on the set to allow saving the orderItem when added to the list on the Order. (Not shown in the mapping)

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜