Java Reference
In-Depth Information
...
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="jpaTemplate"
class="org.springframework.orm.jpa.JpaTemplate">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean name="courseDao"
class="com.apress.springenterpriserecipes.course.jpa.JpaCourseDao">
<property name="jpaTemplate" ref="jpaTemplate" />
</bean>
</beans>
Another advantage of
HibernateTemplate
and
JpaTemplate
is that they will translate
native Hibernate and JPA exceptions into exceptions in Spring's
DataAccessException
hierarchy.
This allows consistent exception handling for all the data access strategies in Spring. For
instance, if a database constraint is violated when persisting an object, Hibernate will
throw an
org.hibernate.exception.ConstraintViolationException
while JPA will throw a
javax.persistence.EntityExistsException
. These exceptions will be translated by
HibernateTemplate
and
JpaTemplate
into
DataIntegrityViolationException
, which is a subclass of Spring's
DataAccessException
.
If you want to get access to the underlying Hibernate session or JPA entity manager in
HibernateTemplate
or
JpaTemplate
in order to perform native Hibernate or JPA operations, you
can implement the
HibernateCallback
or
JpaCallback
interface and pass its instance to the
execute()
method of the template. This will give you a chance to use any implementation-specific features directly
if there's not sufficient support already available from the template implementations.
hibernateTemplate.execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,
SQLException {
// ... anything you can imagine doing can be done here.
➥
Cache invalidation, for example…
}
};
jpaTemplate.execute(new JpaCallback() {
public Object doInJpa(EntityManager em) throws PersistenceException {
// ... anything you can imagine doing can be done here. }
};
Extending the Hibernate and JPA DAO Support Classes
Your Hibernate DAO can extend
HibernateDaoSupport
to have the
setSessionFactory()
and
setHibernateTemplate()
methods inherited. Then, in your DAO methods, you can simply call
the
getHibernateTemplate()
method to retrieve the template instance.
Search WWH ::
Custom Search