4. Code Example

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.

                
@Repository
public class PersonDaoImpl implements PersonDao {

    protected HibernateTemplate template = null;

    /**
     * Sets Hibernate session factory and creates a 
     * <code>HibernateTemplate</code> from it.
     */
    public void setSessionFactory(SessionFactory sessionFactory) {
        template = new HibernateTemplate(sessionFactory);
    }
    
    /**
     * Find all 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.
     */
    public void save(Person person) {
        template.saveOrUpdate(person);
    }

}