One-to-Many Mappings
Hibernate has the capability to model a lot of different kinds of associations. The most common
associations are one-to-many and many-to-many. For each Contact, they will have zero or more
telephone numbers, so it's a one-to-many association (in ORM terms, the one-to-many association is
used to model both zero-to-many and one-to-many relationships within the data structure). Listing 9-8
shows the code snippet for the Contact class for mapping with the ContactTelDetail class.
Listing 9-8. One-to-Many Association
package com.apress.prospring3.ch9.domain;
// Import statements omitted
@Entity
@Table(name = "contact")
public class Contact implements Serializable {
// Other code omitted
private Set<ContactTelDetail> contactTelDetails =
new HashSet<ContactTelDetail>();
@OneToMany(mappedBy = "contact", cascade=CascadeType.ALL,
orphanRemoval=true)
public Set<ContactTelDetail> getContactTelDetails() {
return this.contactTelDetails;
}
public void setContactTelDetails(Set<ContactTelDetail> contactTelDetails) {
this.contactTelDetails = contactTelDetails;
}
public void addContactTelDetail(ContactTelDetail contactTelDetail) {
contactTelDetail.setContact(this);
getContactTelDetails().add(contactTelDetail);
}
public void removeContactTelDetail(ContactTelDetail contactTelDetail) {
getContactTelDetails().remove(contactTelDetail);
}
}
As shown in Listing 9-8, the getter method of the attribute contactTelDetails is annotated
with @OneToMany, which indicates the one-to-many relationship with the ContactTelDetail class.
Several attributes are passed to the annotation. The mappedBy attribute indicates the property in the
ContactTelDetail class that provides the association (i.e., linked up by the foreign key definition in the
CONTACT_TEL_DETAIL table). The cascade attribute means that update operation should cascade to the
child. The orphanRemoval means that after the contact telephone details have been updated, those
entries that no longer exist in the set should be deleted from the database. Listing 9-9 shows the
corresponding code snippet in the ContactTelDetail class for the association mapping.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home