DAO和JDBC的关系? [英] DAO and JDBC relation?

查看:1266
本文介绍了DAO和JDBC的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Hibernate实现ORM(对象关系映射),JDBC实现什么类型的映射?它实现DAO吗?我不完全明白如何/如果DAO与JDBC相关...?

解决方案

DAO不是映射。 DAO表示数据访问对象。它看起来像这样:

  public interface UserDAO {

public用户发现(Long id)throws DAOException;

public void save(User user)throws DAOException;

public void delete(User user)throws DAOException;

// ...
}



< JDBC只是一个实现细节。

  public class UserDAOJDBC implements UserDAO {

public User find(Long id)throws DAOException {
//在这里写入JDBC代码,通过id返回User。
}

// ...
}

Hibernate可以是另一个。




public User find(Long id)throws DAOException {
//这里写Hibernate代码,通过id返回User。
}

// ...
}

JPA 可以是另一个(如果你将一个现有的旧应用程序迁移到JPA;对于新的应用程序,这将是一个有点奇怪,因为JPA本身实际上是DAO,例如Hibernate和EclipseLink作为可用的实现)。



public class UserDAOJPA implements UserDAO {

public User find(Long id)throws DAOException {
//在这里写入JPA代码,通过id返回User。
}

// ...
}

它允许您切换 UserDAO 实现,而不更改使用DAO的业务代码(当然,只有当您正确地编码接口)。



对于JDBC,你只需要写很多行来查找/保存/删除所需的信息,而Hibernate只需要几行代码。



另请参阅:

$ Hiberenate是一个ORM,无论您是否使用DAO, b
$ b

I know that Hibernate implements ORM (Object Relational Mapping), what type of mapping does JDBC implement? Does it implement DAO? I don't totally understand how/if DAO is related to JDBC...?

解决方案

DAO isn't a mapping. DAO stands for Data Access Object. It look something like this:

public interface UserDAO {

    public User find(Long id) throws DAOException;

    public void save(User user) throws DAOException;

    public void delete(User user) throws DAOException;

    // ...
}

For DAO, JDBC is just an implementation detail.

public class UserDAOJDBC implements UserDAO {

    public User find(Long id) throws DAOException {
        // Write JDBC code here to return User by id.
    }

    // ...
}

Hibernate could be another one.

public class UserDAOHibernate implements UserDAO {

    public User find(Long id) throws DAOException {
        // Write Hibernate code here to return User by id.
    }

    // ...
}

JPA could be another one (in case you're migrating an existing legacy app to JPA; for new apps, it would be a bit weird as JPA is by itself actually the DAO, with e.g. Hibernate and EclipseLink as available implementations).

public class UserDAOJPA implements UserDAO {

    public User find(Long id) throws DAOException {
        // Write JPA code here to return User by id.
    }

    // ...
}

It allows you for switching of UserDAO implementation without changing the business code which is using the DAO (only if you're properly coding against the interface, of course).

For JDBC you'll only need to write a lot of lines to find/save/delete the desired information while with Hibernate it's a matter of only a few lines. Hiberenate as being an ORM takes exactly that nasty JDBC work from your hands, regardless of whether you're using a DAO or not.

See also:

这篇关于DAO和JDBC的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆