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.
Solution
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 {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void store(Course course) {
entityManager.merge(course);
}
@Transactional
public void delete(Long courseId) {
Course course = entityManager.find(Course.class, courseId);
entityManager.remove(course);
}
@Transactional(readOnly = true)
public Course findById(Long courseId) {
return entityManager.find(Course.class, courseId);
}
Search WWH ::




Custom Search