lishman levelup
«previous  next»


Getting Started
Form Processing
IoC Container
Hibernate ORM



Data Access Object


Next, we introduce a data access object (DAO). A DAO is an interface which abstracts the data access operations to be performed on a database table.

DAO Interface

This is the DAO for the COUNTRY table:
public interface CountryDao {

  public Collection<Country> getAll();

  public Country getById(int countryId);

  public Country getByName(String countryName);

  public void save(Country country);

  public void delete(Country country);

}

Hibernate Implementation

Now we can add a concrete implementation for the DAO, using Hibernate.
@Repository
@Transactional
public class HibernateCountryDao implements CountryDao {

  @Autowired
  SessionFactory sessionFactory;

  @Transactional(readOnly = true)
  public Country getById(int countryId) {
    return (Country)sessionFactory.getCurrentSession().get(Country.class, countryId);
  }

  @Transactional(readOnly = true)
  public Country getByName(String countryName) {
    return (Country) sessionFactory.getCurrentSession()
                                   .createQuery("from Country ctry " +
                                                "where ctry.name = :name")
                                   .setParameter("name", countryName)
                                   .uniqueResult();
  }

  @Transactional(readOnly = true)
  public Collection<Country> getAll() {
    return sessionFactory.getCurrentSession().createQuery("from Country").list();
  }

  public void save(Country country) {
    sessionFactory.getCurrentSession().merge(country);
  }

  public void delete(Country country) {
    sessionFactory.getCurrentSession().delete(country);
  }

}
The beauty of the DAO is that the implementation can use any persistence technology. Provided the client object uses the DAO interface to perform data access operations, Spring can inject different implementations that use native Hibernate, JPA, JDBC or even mock objects.

Repository Stereotype

The class is annotated with the @Repository stereotype annotation, which can be auto-detected using classpath component scanning, in the same way as @Controller and @ServiceTransactions
Info @Transactional includes many settings to manage the behavior of transactions.
We also include the @Transactional annotation on the class and on several of the methods.

@Transactional at the class level indicates that all public methods on the class are to participate in transactions. The @Transactional annotations on the methods indicate which of the transactions are read only.

Dependency Injection

We can see that an instance of the Hibernate SessionFactory class is automatically injected for us. The Spring framework manages the allocation of Hibernate resources, such as SessionFactory, as we will see in the Spring MVC and Hibernate Configuration section, later.
»