As shown in Listing 10-19, we first retrieve the record with an ID of 1. Then we change the first
name. Then we loop through the telephone objects and retrieve the one with type "Home" and remove it
from the contact's telephone detail property. Finally, we call the ContactService.save() method again.
When you run the program, you will see the following output (other output was omitted):
Contact - Id: 1, First name: Kim Fung, Last name: Ho, Birthday: 1980-07-30
Contact Tel Detail - Id: 1, Contact id: 1, Type: Mobile, Number: 1234567890
Hobby :Movies
Hobby :Swimming
You will see the first name was updated, and the home telephone was removed. The telephone can
be removed because of the orphanRemoval=true attribute that was defined in the one-to-many
association, which instructs the JPA provider (i.e., Hibernate) to remove all orphan records that exist in
database but are no longer found in the object when persisted.
@OneToMany(mappedBy = "contact", cascade=CascadeType.ALL, orphanRemoval=true)
Deleting Data
Deleting data is simple. Just call the EntityManager.remove() method and pass in the contact object.
Listing 10-20 shows the code snippet.
Listing 10-20. Implementing the delete() Method
package com.apress.prospring3.ch10.service.jpa;
// Import statements omitted
@Service("jpaContactService")
@Repository
@Transactional
public class ContactServiceImpl implements ContactService {
private Log log = LogFactory.getLog(ContactServiceImpl.class);
// Other code omitted
public void delete(Contact contact) {
Contact mergedContact = em.merge(contact);
em.remove(mergedContact);
log.info("Contact with id: " + contact.getId()
+ " deleted successfully");
}
}
As shown in Listing 10-20, first the EntityManager.merge() method is invoked to merge the state of the
entity into the current persistence context. The merge() method will return the managed entity instance.
Then the EntityManager.remove() is called, passing in the managed contact entity instance. The remove
operation will delete the contact record, together with all its associated information, including telephone
details and hobbies, as we defined the cascade=CascadeType.ALL in the mapping. To test the delete
operation, add the code snippet in Listing 10-21 into the main() method of the JpaSample class.
Listing 10-21. Testing Delete Operation
// Delete contact
contact = contactService.findById(1l);
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home