Java Reference
In-Depth Information
@Transactional(readOnly = true)
public Course findById(Long courseId) {
return (Course) hibernateTemplate.get(Course.class, courseId);
}
@Transactional(readOnly = true)
public List<Course> findAll() {
return hibernateTemplate.find("from Course");
}
}
In this DAO implementation, you declare all the DAO methods to be transactional with the
@Transactional annotation. Among these methods, findById() and findAll() are read-only. The
template methods in HibernateTemplate are responsible for managing the sessions and transactions.
If there are multiple Hibernate operations in a transactional DAO method, the template methods will
ensure that they will run within the same session and transaction. As a result, you have no need to deal
with the Hibernate API for session and transaction management.
The HibernateTemplate class is thread-safe, so you can declare a single instance of it in the bean
configuration file for Hibernate (i.e., beans-hibernate.xml ) and inject this instance into all Hibernate
DAOs. A HibernateTemplate instance requires the sessionFactory property to be set. You can inject this
property by either setter method or constructor argument.
<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
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
...
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean name="courseDao"
class="com.apress.springenterpriserecipes.course.hibernate.
HibernateCourseDao">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
</beans>
Search WWH ::




Custom Search