问题
Hi I know that and tested before merge will reattach the object back to session preventing lazy initialization exception when object is no longer in session.
a.) So I have a few question.
If i payment --> customer (in a many-to-one unidirectional relationship) and I do
Payment payment = Payment.class.cast(session.merge(oldPayment));
Will customer object also be reattach into session, or do I have to make another merge call for the customer.
b.) What happen if the payment--> customer (many-to-one bidirectional relationship). What would happen than.
c.) How about if i have relationship of more than three hierarchy.
example: hotel --> payment --> customer.
If I do Hotel hotel = Hotel.class.cast(session.merge(unmergeHotel)), will the payment and customer object also be merge into session?
Thanks
回答1:
It's defined by cascading options of your relationships.
- If relationship is configured to cascade merge operations, then entities referenced from the entity being merged will be merged too, so that changes made to these entities before merge will be propagated to the database.
- Otherwise, these entities will be reloaded from the database, therefore any changes made to these entities before merge will be discarded.
- Uninitialized lazy relationships are ignored.
Related exceprt from JPA Specification (I guess native Hibernate's Session
interface offers the same semantics):
- For all entities Y referenced by relationships from X having the cascade element value
cascade=MERGE
orcascade=ALL
, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)- If X is an entity merged to X', with a reference to another entity Y, where
cascade=MERGE
orcascade=ALL
is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.The persistence provider must not merge fields marked LAZY that have not been fetched: it must ignore such fields when merging.
See also:
- JSR 317: Java™ Persistence 2.0
- 11.11. Transitive persistence
来源:https://stackoverflow.com/questions/4895597/hibernate-will-merge-work-with-many-to-one-object-transtively