As shown in Listing 10-18, we create a new contact, add two telephone details, and save the object.
Then we list all the contacts again. Running the program yields the following output (the output of
existing contacts was omitted):
2011-10-19 19:35:54,968 INFO [com.apress.prospring3.ch10.service.jpa.ContactServiceImpl]
<Inserting new contact>
Hibernate: insert into contact (ID, BIRTH_DATE, FIRST_NAME, LAST_NAME, VERSION) values (null,
?, ?, ?, ?)
Hibernate: insert into contact_tel_detail (ID, CONTACT_ID, TEL_NUMBER, TEL_TYPE, VERSION)
values(null, ?, ?, ?, ?)
Hibernate: insert into contact_tel_detail (ID, CONTACT_ID, TEL_NUMBER, TEL_TYPE, VERSION)
values (null, ?, ?, ?, ?)
2011-10-19 19:35:54,992 INFO [com.apress.prospring3.ch10.service.jpa.ContactServiceImpl]
<Contact saved with id: 4>
Listing
contacts with details:
...
Contact
- Id: 4, First name: Michael, Last name: Jackson, Birthday: 2011-10-19
Contact
Tel Detail - Id: 5, Contact id: 4, Type: Mobile, Number: 2222222222
Contact
Tel Detail - Id: 4, Contact id: 4, Type: Home, Number: 1111111111
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 statement being fired to the database.
Updating Data
Updating contacts is as easy as inserting data. Let's go through an example. Suppose for a 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 10-19 into the main() method of the JpaSample class.
Listing 10-19. Testing Update Operation
// Other code omitted
// Find contact by ID
contact = contactService.findById(1l);
System.out.println("");
System.out.println("Contact with id 1:" + contact);
System.out.println("");
// Update contact
contact.setFirstName("Kim Fung");
Set<ContactTelDetail> contactTels = contact.getContactTelDetails();
ContactTelDetail toDeleteContactTel = null;
for (ContactTelDetail contactTel: contactTels) {
if (contactTel.getTelType().equals("Home")) {
toDeleteContactTel = contactTel;
}
}
contactTels.remove(toDeleteContactTel);
contactService.save(contact);
contacts = contactService.findAllWithDetail();
listContactsWithDetail(contacts);
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home