Java Reference
In-Depth Information
Ideally, we would like to dictate that only changes to one end of the relationship will result
in any updates to the foreign key; and indeed, Hibernate allows us to do this by marking one
end of the association as being managed by the other (in the XML mapping files, this is known
as the “ inverse ” of the parent, whereas in the EJB 3 terminology used by the annotation map-
pings, it is marked as being “ mappedBy ” the parent).
n Caution inverse and mappedBy are purely about how the foreign key relationships between entities
are saved. They have nothing to do with saving the entities themselves. Despite this, they are often confused
with the entirely orthogonal cascade functionality (described in the “Cascading Operations” section of this
chapter).
While Hibernate lets us specify that changes to one association will result in changes to the
database, it does not allow us to cause changes to one end of the association to be automati-
cally reflected in the other end in the Java POJOs. For example, in a one-to-one bidirectional
association between an Email class and a Message class, the code in Listing 4-2 is incomplete
even if the Message entity is the inverse of the Email entity:
Listing 4-2. A Common Misconception About Bidirectional Associations
Email email = new Email("Test Email");
Message message = new Message("Test Message");
email.setMessage(message);
// Incorrectly managed
session.save(email);
session.save(message);
System.out.println(message.getEmail());
The final call to message.getEmail() will return null (assuming simple getters and setters
are used). To get the desired effect, both entities must be updated—If the Email entity owns the
association, this merely ensures the proper assignment of a foreign key column value. There is
no implicit call of message.setEmail(email) . This must be explicitly given as in Listing 4-3.
Listing 4-3. The Correct Maintenance of a Bidirectional Association
Email email = new Email("Test Email");
Message message = new Message("Test Message");
email.setMessage(message);
message.setEmail(email); // Correctly managed
session.save(email);
session.save(message);
System.out.println(message.getEmail());
It is common for users new to Hibernate to get confused about this point—the confusion
arises from two origins, which are described in the following paragraphs.
Search WWH ::




Custom Search