Java Reference
In-Depth Information
Table 3-4.
Spring's Support Classes for Different Data Access Strategies
Support Class
JDBC
Hibernate
JPA
Template class
JdbcTemplate
HibernateTemplate
JpaTemplate
JdbcDaoSupport
HibernateDaoSupport
JpaDaoSupport
DAO support
DataSourceTransaction
HibernateTransaction
JpaTransactionManager
Transaction
Spring defines the
HibernateTemplate
and
JpaTemplate
classes to provide template methods for
different types of Hibernate and JPA operations to minimize the effort involved in using them. The
template methods in
HibernateTemplate
and
JpaTemplate
ensure that Hibernate sessions and JPA entity
managers will be opened and closed properly. They will also have native Hibernate and JPA transactions
participate in Spring-managed transactions. As a result, you will be able to manage transactions
declaratively for your Hibernate and JPA DAOs without any boilerplate transaction code.
How It Works
Using a Hibernate Template and a JPA Template
First, the
HibernateCourseDao
class can be simplified as follows with the help of Spring's
HibernateTemplate
:
package com.apress.springenterpriserecipes.course.hibernate;
...
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
public class HibernateCourseDao implements CourseDao {
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
@Transactional
public void store(Course course) {
hibernateTemplate.saveOrUpdate(course);
}
@Transactional
public void delete(Long courseId) {
Course course = (Course) hibernateTemplate.get(Course.class, courseId);
hibernateTemplate.delete(course);
}
Search WWH ::
Custom Search