Java Reference
In-Depth Information
package com.apress.springenterpriserecipes.course.hibernate;
...
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;
public class HibernateCourseDao
extends HibernateDaoSupport implements
CourseDao {
@Transactional
public void store(Course course) {
getHibernateTemplate().saveOrUpdate(course);
}
@Transactional
public void delete(Long courseId) {
Course course = (Course)
getHibernateTemplate().get(Course.class,
courseId);
getHibernateTemplate().delete(course);
}
@Transactional(readOnly = true)
public Course findById(Long courseId) {
return (Course)
getHibernateTemplate().get(Course.class, courseId);
}
@Transactional(readOnly = true)
public List<Course> findAll() {
return
getHibernateTemplate().find("from Course");
}
}
Because
HibernateCourseDao
inherits the
setSessionFactory()
and
setHibernateTemplate()
methods, you can inject either of them into your DAO so that you can retrieve the
HibernateTemplate
instance. If you inject a session factory, you will be able to delete the
HibernateTemplate
declaration.
<bean name="courseDao"
class="com.apress.springenterpriserecipes.course.hibernate.HibernateCourseDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Similarly, your JPA DAO can extend
JpaDaoSupport
to have
setEntityManagerFactory()
and
setJpaTemplate()
inherited. In your DAO methods, you can simply call the
getJpaTemplate()
method
to retrieve the template instance. This instance will contain the pre-initialized
EntityManagerFactory
.
package com.apress.springenterpriserecipes.course.jpa;
...
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;
Search WWH ::
Custom Search