Question

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

Was it helpful?

Solution

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 or cascade=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 or cascade=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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top