Listing 10-16. Testing the findAll() Method Using the Constructor Expression
// Contact summary with constructor expression
ContactSummaryService contactSummaryService =
ctx.getBean("contactSummaryService",ContactSummaryService.class);
List<ContactSummary> contacts = contactSummaryService.findAll();
for (ContactSummary contactSummary: contacts) {
System.out.println(contactSummary);
}
Executing the ContactSummarySample class again will produce the output for each ContactSummary
object within the list, as shown here (other output was omitted):
First name: Clarence Last Name: Ho Home Phone: 1234567890
First name: Scott Last Name: Tiger Home Phone: 1234567890
As you can see, the constructor expression is very useful for mapping the result of a custom query
into POJOs for further application processing.
Inserting Data
Insert data in JPA is very simple. Like Hibernate, JPA also supports retrieving a database-generated
primary key. Listing 10-17 shows the implementation of the save() method.
Listing 10-17. Implementing the save() Method
package com.apress.prospring3.ch10.service.jpa;
// Import statements omitted
@Service("jpaContactService")
@Repository
@Transactional
public class ContactServiceImpl implements ContactService {
// Other code omitted
public Contact save(Contact contact) {
if (contact.getId() == null) { // Insert Contact
log.info("Inserting new contact");
em.persist(contact);
} else {
// Update Contact
em.merge(contact);
log.info("Updating existing contact");
}
log.info("Contact saved with id: " + contact.getId());
return contact;
}
}
As shown in Listing 10-17, the save() method first checks whether the object is a new entity
instance, by checking the id value. If id is null (i.e., not yet assigned), then it's a new entity instance, and
the EntityManager.persist() method will be invoked. When calling the persist() method, the
EntityManager will persist the entity and make it a managed instance within the current persistence
context. If the id value exists, then it's an update, and the EntityManager.merge() method will be called
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home