Java Reference
In-Depth Information
<context:annotation-config />
...
</beans>
This bean post processor can also inject the entity manager factory into a property with the
@PersistenceUnit
annotation. This allows you to create entity managers and manage transactions
by yourself. It's no different from injecting the entity manager factory via a setter method.
package com.apress.springenterpriserecipes.course.jpa;
...
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
public class JpaCourseDao implements CourseDao {
@PersistenceContext
private EntityManager entityManager;
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
...
}
Remember that
JpaTemplate
will translate the native JPA exceptions into exceptions in Spring's
DataAccessException
hierarchy. However, when calling native methods on a JPA entity manager, the
exceptions thrown will be of native type
PersistenceException
, or other Java SE exceptions like
IllegalArgumentException
and
IllegalStateException
. If you want JPA exceptions to be translated
into Spring's
DataAccessException
, you have to apply the
@Repository
annotation to your DAO class.
package com.apress.springenterpriserecipes.course.jpa;
...
import org.springframework.stereotype.Repository;
@Repository("courseDao")
public class JpaCourseDao implements CourseDao {
...
}
Then register a
PersistenceExceptionTranslationPostProcessor
instance to translate the
native JPA exceptions into exceptions in Spring's
DataAccessException
hierarchy. You can also enable
<context:component-scan>
and delete the original
JpaCourseDao
bean declaration because
@Repository
is a stereotype annotation in Spring 2.5 and beyond.
<beans ...>
...
<context:component-scan
base-package="com.apress.springenterpriserecipes.course.jpa" />
<bean class="org.springframework.dao.annotation.PersistenceException
➥
Translation PostProcessor" />
</beans>
Search WWH ::
Custom Search