0

This is my OrderSet.hbm file. It has OrderSetMembers as it's child (one-to-many) relationship.

<list name="orderSetMembers" lazy="true" cascade="all-delete-orphan" inverse="true">
    <key column="order_set_id" not-null="true"/>
    <list-index column="sequence_number"/>
    <one-to-many class="OrderSetMember" />
</list>

This is my OrderSetMember.hbm file. OrderSetMember has a many-to-one relationship with its parent. I wanted a bi-directional mapping.

<many-to-one name="orderSet" class="OrderSet">
    <column name="order_set_id"/>
</many-to-one>

Can the parent and the child both be saved with one session-save command? Or do I need to have another session save to save the child as well?

Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(orderSet);

These are my data-models:

public class OrderSet {
    private List<OrderSetMember> orderSetMembers;
}


public class OrderSetMember {
    private OrderSet orderSet;
}
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110

1 Answers1

0

cascade and inverse have two completely different purposes.

cascade tells which entity lifecycle operation should be automatically applied on child(ren) when applied on parent.

inverse means that child is the owner of the association. That further means that if you don't associate child with the parent on the child side, the relationship information is not going to be synchronized with the database.

For example, if you add an OrderSetMember to the orderSetMembers collection in the parent entity instance, but you leave orderSet field null in the OrderSetMember instance, and then invoke session.saveOrUpdate(orderSet), the outcome will be:

  1. Both OrderSet and OrderSetMember instances are saved to the database (save is cascaded to the children).
  2. order_set_id (foreign key in the table to which OrderSetMember is mapped) is set to null. This is because OrderSetMember is the owner of the association, and there was no associated OrderSet entity when Hibernate inspected the owner of the association at dirty-check time.
  3. When you read the above OrderSet instance in a new session, you'll notice that the OrderSetMember is not present in the orderSetMembers collection either.
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110