2. 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.

The @Transactional annotation configures the class and all it's methods for read only access, but the save method overrides this by specifying it's own annotation of @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW).

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 (Collection<Person>) template.find("from Person");
    }
    
    /**
     * Find persons by last name.
     */
    @SuppressWarnings("unchecked")
    public Collection<Person> findPersonsByLastName(String lastName) throws DataAccessException {
        return (Collection<Person>) 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);
    }

}