contact.setLastName("Jackson");
contact.setBirthDate(new Date());
ContactTelDetail contactTelDetail =
new ContactTelDetail("Home", "1111111111");
contact.addContactTelDetail(contactTelDetail);
contactTelDetail = new ContactTelDetail("Mobile", "2222222222");
contact.addContactTelDetail(contactTelDetail);
contactDao.save(contact);
contacts = contactDao.findAllWithDetail();
listContactsWithDetail(contacts);
As shown in Listing 9-23, we create a new contact, add two telephone details, and save the object.
Afterward, we list all the contacts again. Running the program yields the following output:
Hibernate: insert into contact_tel_detail (ID, CONTACT_ID, TEL_NUMBER, TEL_TYPE, VERSION)
values (null, ?, ?, ?, ?)
2011-10-13 15:25:52,405 INFO [com.apress.prospring3.ch9.dao.hibernate.ContactDaoImpl] -
<Contact saved with id: 4>
Listing contacts with details:
Contact - Id: 1, First name: Clarence, Last name: Ho, Birthday: 1980-07-30
Contact Tel Detail - Id: 1, Contact id: 1, Type: Mobile, Number: 1234567890
Contact Tel Detail - Id: 2, Contact id: 1, Type: Home, Number: 1234567890
Hobby :Swimming
Hobby :Movies
Contact - Id: 4, First name: Michael, Last name: Jackson, Birthday: 2011-10-13
Contact Tel Detail - Id: 4, Contact id: 4, Type: Mobile, Number: 2222222222
Contact Tel Detail - Id: 5, Contact id: 4, Type: Home, Number: 1111111111
Contact - Id: 3, First name: John, Last name: Smith, Birthday: 1964-02-28
Contact - Id: 2, First name: Scott, Last name: Tiger, Birthday: 1990-11-02
Contact Tel Detail - Id: 3, Contact id: 2, Type: Home, Number: 1234567890
Hobby :Swimming
From the INFO log record, you can see that the id of the newly saved contact was populated
correctly. Hibernate will also show all the SQL statements being fired to the database so you know what
is actually happening behind the scenes.
Updating Data
Updating a contact is as easy as inserting data. Let's go through an example. Suppose for the contact
with an ID of 1, we want to update its first name and remove the home telephone record. To test the
update operation, add the code snippet in Listing 9-24 into the SpringHibernateSample class.
Listing 9-24. Testing Update Operation
// Update contact
contact = contactDao.findById(1l);
contact.setFirstName("Kim Fung");
Set<ContactTelDetail> contactTels = contact.getContactTelDetails();
ContactTelDetail toDeleteContactTel = null;
for (ContactTelDetail contactTel: contactTels) {
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home