DAO and JDBC relation?

给你一囗甜甜゛ 提交于 2019-12-17 22:38:34

问题


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...?


回答1:


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:

  • I found JPA, or alike, don't encourage DAO pattern
  • JSF Controller, Service and DAO



回答2:


DAO is an abstraction for accessing data, the idea is to separate the technical details of data access from the rest of the application. It can apply to any kind of data.

JDBC is an API for accessing relational databases using Java.

JDBC is more low-level than an ORM, it maps some Java types to SQL types but no more than that, it just takes DDL and DML, executes it, and returns result sets. It's up to your program to make sense of it.



来源:https://stackoverflow.com/questions/7070467/dao-and-jdbc-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!