Data Access Objects DAO

Applications need to access any kind of persistent storage. As you are learning Hibernate you probably intend to use a database as persistent storage.

But persistent storage is not limited to databases. Any kind of LDAP directories holding user and user roles, external messaging systems etc. are persistent storages.

A DAO class encapsulates data sources and the used query language and provides a well defined set of methods for your application.

Imagine a userDao class providing an interface as shown in the next figure. When your application only deals with the interface userDao when accessing user information, you can easily replace it with an implementation using a different database or a LDAP directory. This is the main intention of the Dao pattern.

public interface UserDao {
   public User findById(Integer id);
   public List findAll();
   public void save(User user);
   public void delete(User user);
}

get a PostgreSQL user Dao

UserDao userDao = new UserDaoPostgreSQL();

or a LDAP userDao

UserDao userDao = new UserDaoLdap();

Hibernate does slightly change the look of this pattern. If you use plain JDBC you would create a Dao for each different database you want support. When using Hibernate this is no longer needed. Hibernate supports multiple database dialects just by changing the configuration.

Therefore, the content of a Hibernate DAO can be quite simple.

.... snip ....
   public User findById(Integer id) {
      return (User) getSession().get(User.class, id);
   }

   public List findAll() {
      return getSession().createQuery("from User").list();
   }

   public void save(User user) {
         session.save(user);
   }
.... snip ....