Java Reference
In-Depth Information
Building DAOs
The DAO pattern is well known to most developers. The idea is to separate out the POJOs from
the logic used to persist them into, and retrieve them from, the database. The specifics of the
implementation vary—at one extreme, they can be provided as interfaces instantiated from
a factory class, allowing a completely pluggable database layer. For our example, we have
selected a compromise of concrete DAO classes. Each DAO class represents the operations
that can be performed on a POJO type.
We have already described the base class
DAO
in Listing 3-15, and the preceding examples
made use of this.
To help encapsulate the specifics of the database operations that are being carried out, we
catch any
HibernateException
that is thrown and wrap it in a business
AdException
instance,
as shown in Listing 3-19.
Listing 3-19.
The
AdException
Class for the Example
package sample;
public class AdException extends Exception {
public AdException(String message) {
super(message);
}
public AdException(String message, Throwable cause) {
super(message,cause);
}
}
The
UserDAO
provides all the methods required to retrieve an existing
User
object, delete
an existing
User
object, or create a new
User
object (see Listing 3-20). Changes to the object
in question will be persisted to the database at the end of the transaction.
Listing 3-20.
The
UserDAO
Class for the Example
package sample.dao;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import sample.AdException;
import sample.entity.User;
public class UserDAO extends DAO {
public UserDAO() {
}
Search WWH ::
Custom Search