contactService.delete(contact);
contacts = contactService.findAllWithDetail();
listContactsWithDetail(contacts);
The previous listing retrieves the contact with an ID of 1 and then calls the delete() method to
delete the contact information. Running the program will produce the following output (other output
was omitted):
Listing
contacts with details:
Contact
- Id: 4, First name: Michael, Last name: Jackson, Birthday: 2011-10-13
Contact
Tel Detail - Id: 4, Contact id: 4, Type: Home, Number: 1111111111
Contact
Tel Detail - Id: 5, Contact id: 4, Type: Mobile, Number: 2222222222
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
You can see that the contact with an ID of 1 was deleted.
Native Query
Having discussed performing trivial database operations using JPA, now let's proceed to some more
advanced topics. Sometimes you may want to have absolute control over the query that will be
submitted to the database. One example is using a hierarchical query in an Oracle database. This kind of
query is database-specific and referred to as a native query.
JPA supports the execution of native queries; the EntityManager will submit the query to the
database as is, without any mapping or transformation performed. You may wonder why we don't use
JDBC directly if JDBC supports direct submission of queries to the database. Spring also provides nice
support for programming JDBC access logic and performs row mapping back to Java POJOs.
One main benefit of using JPA native queries is the mapping of the resultset back to the ORM-
mapped entity classes. The following two sections discuss how to use a native query to retrieve all
contacts and directly map the resultset back to the Contact objects.
Simple Native Query
To demonstrate how to use a native query, let's implement a new method to retrieve all the contacts from
the database using a native query. Listing 10-22 shows the new method in the ContactService interface.
Listing 10-22. The findAllByNativeQuery() Method
package com.apress.prospring3.ch10.service;
// Other code omitted
public interface ContactService {
// Other code omitted
// Find all contacts by native query
public List<Contact> findAllByNativeQuery();
}
Listing 10-23 shows the implementation of the findAllByNativeQuery() method.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home