The Hibernate SessionFactory
is used to create a HibernateTemplate
as it's set. The template is
then used for any Hibernate database operations. Spring's HibernateTemplate
converts all exceptions
to runtime exceptions so it isn't necessary to handle any exceptions.
The @Transactional
annotation isn't used in this example because there isn't anything
configuring transactions in the Spring configuration.
Example 1. PersonDaoImpl
@Repository @Transactional(readOnly = true) public class PersonDaoImpl implements PersonDao { protected HibernateTemplate template = null; /** * Sets Hibernate session factory. */ public void setSessionFactory(SessionFactory sessionFactory) { template = new HibernateTemplate(sessionFactory); } /** * Find persons. */ @SuppressWarnings("unchecked") public Collection<Person> findPersons() throws DataAccessException { return template.find("from Person"); } /** * Find persons by last name. */ @SuppressWarnings("unchecked") public Collection<Person> findPersonsByLastName(String lastName) throws DataAccessException { return template.find("from Person p where p.lastName = ?", lastName); } /** * Saves person. */ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public void save(Person person) { template.saveOrUpdate(person); } }