开发者

relationship between DAO and hibernate

I tried to google the answer, but I am still puzzled about their relationship. I speculate Hibernate is a kind of DAO. And I looked up DAO in Wikipedia, DAO

But found there is nothing related with hibernate there. So what exactly is t开发者_JAVA技巧he relationship between the two? Some examples will be great!


No, Hibernate is an Object-Relational-Mapper (see also Object-relational impedance mismatch).

DAO is a design pattern that is technology independent. DAOs on the Java platform usually use one (usually only one) of the following technologies: JDBC, Hibernate, JPA, JDO

So you can use Hibernate without using DAOs (although it's rarely a good idea) and you certainly can create DAOs without using Hibernate. Nevertheless, about 50% of all Java DAO classes are created using either plain Hibernate or JPA with Hibernate as JPA provider.


DAO generally describes the interface between your application and the underlying database. You can implement this functionallity by using a Object-Relational-Mapper - which Hibernate is.

Don't think I can describe it better - sorry.


The Data Access Object is just that: an object for accessing the data. It is typically an interfaced layer of an application that performs some business function. The DAO may use hibernate to talk to a database, read from a file, talk to a remote resource or anything else. The point is the upper layers of the application don't know or need to care.

Hibernate is just one of the many ways in which you can implement a DAO.

public interface BusinessOperation {
    public String bestVehicle(String show);
}

// Hibernate implementation of DAO
public class HibernateBusinessOperation implements BusinessOperation {
    @Override
    public String bestVehicle(String show) {
        String sql = "FROM show where show_name = :show";
        Query query = getSession().createQuery(sql);
        query.setString("show", show);
        Show queryResult = (Show) query.uniqueResult();
        if (queryResult == null)
          throw new InvalidShowException(show);
        return queryResult->getBestVehicle();
    }
}

// Test implementation of DAO
public class TestBusinessOperation implements BusinessOperation {
    @Override
    public String bestVehicle(String show) {
        if ("Knight Rider".equals(show)) {
            return "KITT";
        }
        if ("Airwolf".equals(show)) {
            return "Airwolf";
        }
        throw new InvalidShowException(show);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜