Listing 9-9. One-to-Many Mapping in ContactTelDetail
package com.apress.prospring3.ch9.domain;
// Import statements omitted
@Entity
@Table(name = "contact_tel_detail")
public class ContactTelDetail implements Serializable {
// Other code omitted
private Contact contact;
@ManyToOne
@JoinColumn(name = "CONTACT_ID")
public Contact getContact() {
return this.contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public String toString() {
return "Contact Tel Detail - Id: " + id + ", Contact id: "
+ getContact().getId() + ", Type: "
+ telType + ", Number: " + telNumber;
}
}
From the previous listing, we annotated the getter method of the contact attribute with @ManyToOne,
which indicates it's the other side of the association from Contact. We also specified the @JoinColumn
annotation for the underlying foreign key column name. Finally, the toString() method was overridden
to facilitate testing the example code later.
Many-to-Many Mappings
Let's move on to see the many-to-many mapping between the Contact and Hobby classes. Every
contact has zero or more hobbies, and each hobby will also be linked up with zero or more contacts.
So, it's a many-to-many mapping. A many-to-many mapping requires a join table, which is the
CONTACT_HOBBY_DETAIL table in Figure 9-4. Listing 9-10 shows the code snippet in the Contact class to
model the relationship.
Listing 9-10. Many-to-Many Association
package com.apress.prospring3.ch9.domain;
// Import statements omitted
@Entity
@Table(name = "contact")
public class Contact implements Serializable {
// Rest of code omitted
private Set<Hobby> hobbies = new HashSet<Hobby>();
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home