Java Reference
In-Depth Information
public class JpaCourseDao
extends JpaDaoSupport implements CourseDao {
@Transactional
public void store(Course course) {
getJpaTemplate().merge(course);
}
@Transactional
public void delete(Long courseId) {
Course course =
getJpaTemplate().find(Course.class, courseId);
getJpaTemplate().remove(course);
}
@Transactional(readOnly = true)
public Course findById(Long courseId) {
return
getJpaTemplate().find(Course.class, courseId);
}
@Transactional(readOnly = true)
public List<Course> findAll() {
return
getJpaTemplate().find("from Course");
}
}
Because
JpaCourseDao
inherits both
setEntityManagerFactory()
and
setJpaTemplate()
, you can
inject either of them into your DAO. If you inject an entity manager factory, you will be able to delete the
JpaTemplate
declaration.
<bean name="courseDao"
class="com.apress.springenterpriserecipes.course.jpa.JpaCourseDao">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
3-10. Persisting Objects with Hibernate's Contextual Sessions
Problem
Spring's
HibernateTemplate
can simplify your DAO implementation by managing sessions and
transactions for you. However, using
HibernateTemplate
means your DAO has to depend on
Spring's API.
Solution
An alternative to Spring's
HibernateTemplate
is to use Hibernate's contextual sessions. In Hibernate 3,
a session factory can manage contextual sessions for you and allows you to retrieve them by the
getCurrentSession()
method on
org.hibernate.SessionFactory
. Within a single transaction, you will
get the same session for each
getCurrentSession()
method call. This ensures that there will be only one
Hibernate session per transaction, so it works nicely with Spring's transaction management support.
Search WWH ::
Custom Search