This is my OrderSet.hbm
file. It has OrderSetMember
s 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;
}
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:
OrderSet
and OrderSetMember
instances are saved to the database ( save
is cascaded to the children). 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. OrderSet
instance in a new session, you'll notice that the OrderSetMember
is not present in the orderSetMembers
collection either.
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.