Java Reference
In-Depth Information
Similarly, Spring provides JpaTemplate to simplify your DAO implementation by managing entity
managers and transactions for you. However, using Spring's JpaTemplate means your DAO is dependent
on Spring's API.
An alternative to Spring's JpaTemplate is to use JPA's context injection. Originally, the @PersistenceContext
annotation is used for entity manager injection in EJB components. Spring can also interpret this
annotation by means of a bean post processor. It will inject an entity manager into a property with this
annotation. Spring ensures that all your persistence operations within a single transaction will be handled
by the same entity manager.
How It Works
To use the context injection approach, you can declare an entity manager field in your DAO and
annotate it with the @PersistenceContext annotation. Spring will inject an entity manager into this field
for you to persist your objects.
package com.apress.springenterpriserecipes.course.jpa;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
public class JpaCourseDao implements CourseDao {
private EntityManager entityManager;
public void store(Course course) {
public void delete(Long courseId) {
Course course = entityManager.find(Course.class, courseId);
@Transactional(readOnly = true)
public Course findById(Long courseId) {
return entityManager.find(Course.class, courseId);
Search WWH ::

Custom Search