contactTelDetail.setTelType("Home");
contactTelDetail.setTelNumber("111111");
contactTelDetails.add(contactTelDetail);
contactTelDetail = new ContactTelDetail();
contactTelDetail.setTelType("Mobile");
contactTelDetail.setTelNumber("222222");
contactTelDetails.add(contactTelDetail);
contact.setContactTelDetails(contactTelDetails);
Set<Hobby> hobbies = new HashSet<Hobby>();
Hobby hobby = new Hobby();
hobby.setHobbyId("Jogging");
hobbies.add(hobby);
contact.setHobbies(hobbies);
contactService.save(contact);
contacts = contactService.findAllWithDetail();
listContactsWithDetail(contacts);
In Listing 11-40, a new contact is constructed, and two telephone records and one hobby record are
created too. Then the save() method of ContactService is invoked. Running the program will produce
the following output (other output was omitted):
Contact - Id: 4, First name: Michael, Last name: Jackson, Birthday: Wed Oct 26 00:00:00 CST
2011
Contact Tel Detail - Id: 4, Contact id: 4, Type: Home, Number: 111111
Contact Tel Detail - Id: 5, Contact id: 4, Type: Mobile, Number: 222222
Hobby :Jogging
You can see that a new contact with an ID of 4 was created, and the data was populated correctly.
Updating Data
Updating contact data is a bit complicated, mostly for the one-to-many telephone and many-to-many
hobby associations. Let's implement the update method with the following sequence of operations:
Update the contact record.
1.
Before updating the telephone details, retrieve the existing telephone details
2.
for the contact, and store the list of IDs for removing orphan records.
For each telephone detail, check whether the ID exists. If it does not exist,
3.
insert a new one. Otherwise, update the existing one. Also, remove the ID from
the list of orphan records. After updating all the telephone details, check the
list of IDs for any orphan telephone detail records. If any orphan telephone
records exist, delete them.
For hobbies, first delete all the existing mappings from the
4.
CONTACT_HOBBY_DETAIL table and then insert the ones within the updated
Contact object.
This sequence is just a typical handling mechanism; you can fine-tune it to suit your specific needs.
First we need to add the update operation in the ContactMapper interface and XML file. Listings 11-41
and 11-42 show the respective code snippets.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home