Java Reference
In-Depth Information
In the bean configuration file for Hibernate (i.e.,
beans-hibernate.xml
), you have to declare
a
HibernateTransactionManager
instance for this application and enable declarative transaction
management via
<tx:annotation-driven>
.
<beans xmlns="
http://www.springframework.org/schema/beans"
xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="
http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
...
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean name="courseDao"
class="com.apress.springenterpriserecipes.course.hibernate.
➥
HibernateCourseDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Remember that
HibernateTemplate
will translate the native Hibernate exceptions into exceptions
in Spring's
DataAccessException
hierarchy. This allows consistent exception handling for different data
access strategies in Spring. However, when calling the native methods on a Hibernate session, the
exceptions thrown will be of native type
HibernateException
. If you want the Hibernate exceptions to
be translated into Spring's
DataAccessException
for consistent exception handling, you have to apply
the
@Repository
annotation to your DAO class that requires exception translation.
package com.apress.springenterpriserecipes.course.hibernate;
...
import org.springframework.stereotype.Repository;
@Repository
public class HibernateCourseDao implements CourseDao {
...
}
Then register a
PersistenceExceptionTranslationPostProcessor
instance to translate the native
Hibernate exceptions into data access exceptions in Spring's
DataAccessException
hierarchy. This bean
post processor will only translate exceptions for beans annotated with
@Repository
.
<beans ...>
...
<bean class="org.springframework.dao.annotation.
➥
PersistenceExceptionTranslationPostProcessor" />
</beans>
Search WWH ::
Custom Search