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="orders" 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)
The above mapping satisfies
Hope this helps.