Once the EntityManagerFactory had been properly configured, injecting it into your service layer
classes is very simple. Listing 10-3 shows the code snippet for the ContactServiceImpl class, which we
will use as the sample for performing database operations using JPA.
Listing 10-3. Injection of EntityManager
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);
@PersistenceContext
private EntityManager em;
// Other code omitted
}
As shown in Listing 10-3, several annotations were applied to the class. The @Service annotation
is to identify that it's a Spring component that provides business services to another layer and assigns
the Spring bean the name jpaContactService. The @Repository annotation indicates that the class
contains data access logic and instructs Spring to translate the vendor-specific exceptions to Spring's
DataAccessException hierarchy. Actually, you can use @Repository("jpaContactService") and get rid of
the @Service annotation; the effect is the same. Here we just use the @Service annotation to indicate it
belongs to the service layer (like @Controller indicates the component is in the web layer) because it is
more developer-friendly. As you will be already familiar, the @Transactional annotation is for defining
transaction requirements.
To inject the EntityManager, we use the @PersistenceContext annotation, which is the standard
JPA annotation for entity manager injection. You may wonder why we're using the different name
(@PersistenceContext) to inject the entity manager, but if you consider that the persistence context is
managed by EntityManager, the annotation makes perfect sense. If you have multiple persistence units in
your application, you can also add the unitName attribute to the annotation to specify which persistence
unit you want to be injected. Typically, a persistence unit represents an individual backend
datasource.
Upon the injection of EntityManager, we are now ready to perform database operations, which will
be discussed in the next section.
Database Operations with JPA
In this section, we will discuss how to perform database operations in JPA.
Listing 10-4 shows the ContactService interface, which indicates the contact information services
we are going to provide.
Listing 10-4. The ContactService Interface
package com.apress.prospring3.ch10.service;
import java.util.List;
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home