Java Reference
In-Depth Information
How It Works
To use the contextual session approach, your DAO methods require access to the session factory, which
can be injected via a setter method or a constructor argument. Then, in each DAO method, you get the
contextual session from the session factory and use it for object persistence.
package com.apress.springenterpriserecipes.course.hibernate;
...
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
public class HibernateCourseDao implements CourseDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Transactional
public void store(Course course) {
sessionFactory.getCurrentSession().saveOrUpdate(course);
}
@Transactional
public void delete(Long courseId) {
Course course = (Course) sessionFactory.getCurrentSession().get(
Course.class, courseId);
sessionFactory.getCurrentSession().delete(course);
}
@Transactional(readOnly = true)
public Course findById(Long courseId) {
return (Course) sessionFactory.getCurrentSession().get(
Course.class, courseId);
}
@Transactional(readOnly = true)
public List<Course> findAll() {
Query query = sessionFactory.getCurrentSession().createQuery(
"from Course");
return query.list();
}
}
Note that all your DAO methods must be made transactional. This is required because Spring wraps
the SessionFactory with a proxy that expects that Spring's transaction management is in play when
methods on a session are made. It will attempt to find a transaction and then fail, complaining that no
Hibernate session's been bound to the thread. You can achieve this by annotating each method or the
entire class with @Transactional . This ensures that the persistence operations within a DAO method
will be executed in the same transaction and hence by the same session. Moreover, if a service layer
component's method calls multiple DAO methods, and it propagates its own transaction to these
methods, then all these DAO methods will run within the same session as well.
Search WWH ::




Custom Search