Java Reference
In-Depth Information
System.out.println("Retrieved...");
System.out.println(email);
System.out.println(email.getMessage());
System.out.println(message);
System.out.println(message.getEmail());
endTransaction();
closeSession();
If you run the code from Listing 4-4, you will see the following output:
Stored...
Test Email
Test Message
Test Message
null
Retrieved...
Test Email
Test Message
Test Message
Test Emails
When the entities are initially stored, the
Message
object's reference to its associated
Email
is
null
, even after Hibernate has stored the data. The entity in memory is not updated to reflect
the change to the
Email
entity. However, after we have closed the session, opened a new one,
and loaded the entities from the database, the entity has been updated.
Because the session has been closed, the session is forced to reload the entities from the
database when we request them by primary key. Because the
Email
entity is the owner of the
association, the association exists in the database purely in the form of a foreign key relation-
ship from the
Email
table onto the
Message
table's primary key. When we altered the
Email
entity
and saved it, this foreign key relationship was therefore updated. So, when we reload the enti-
ties, the
Message
entity's association details are (correctly) obtained from the same foreign key.
If we alter this code to make the association in the
Message
entity instead of the
Email
entity, but leave the
Email
entity the owner of the association, we will see the reverse effect, as
follows:
Email email = new Email("Test Email");
Message message = new Message("Test Message");
//email.setMessage(message);
message.setEmail(email);
Because we have not made the association in the
Email
entity (the owner), the foreign key
of the
Email
table is not pointed at the
Message
table. When we reload the entities, we do not
see the “automatic” association behavior—quite the opposite:
Stored...
Test Email
null
Test Message
Test Email
Search WWH ::
Custom Search