Java 新手 - 什么是 JPA 和 DAO?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15554826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:02:29  来源:igfitidea点击:

New to Java - What's JPA and DAO?

javajpaejbdao

提问by mimipc

I'm new to Java and i'm trying to make a web project with servlets. I'd like to query my database but I think I don't understand everything about JPA and DAO.

我是 Java 新手,正在尝试使用 servlet 制作一个 Web 项目。我想查询我的数据库,但我想我不了解 JPA 和 DAO 的所有内容。

I've been taught to do things this way :

我被教导要这样做:

  • Create class com.package.entity.User (generated from my database)
  • Create interface com.package.dao.UserDao
  • Create class com.package.dao.jpa.JpaUserDao implementing UserDao
  • Create EJB com.package.service.UserService with methods like public List<User> findAll()
  • 创建类 com.package.entity.User(从我的数据库生成)
  • 创建接口 com.package.dao.UserDao
  • 创建类 com.package.dao.jpa.JpaUserDao 实现 UserDao
  • 使用类似的方法创建 EJB com.package.service.UserService public List<User> findAll()

I've heard there's no need to create a DAO interface with JPA but I'm completely lost and I don't understand at all what I should do or what an EJB is. I simply want to find all the users in my database and display their names following Java's good practices.

我听说没有必要用 JPA 创建 DAO 接口,但我完全迷失了,我根本不明白我应该做什么或 EJB 是什么。我只是想在我的数据库中找到所有用户并按照 Java 的良好实践显示他们的名字。

It's allready OK for my servlets and JSPs.

对我的 servlet 和 JSP 来说已经没问题了。

What would you recommend ?

你会推荐什么 ?

回答by Dave

DAO stands for "Data Access Object". It abstracts the concept of "getting something from a datastore". Your DAO objects can be implemented with JDBC calls, JPA calls or whatever. Maybe it calls some remote webservice. Having a DAO over JPA seems redundant and it does add a layer, but I think it is worth it.

DAO 代表“数据访问对象”。它抽象了“从数据存储中获取一些东西”的概念。您的 DAO 对象可以通过 JDBC 调用、JPA 调用或其他方式实现。也许它调用了一些远程网络服务。在 JPA 上使用 DAO 似乎是多余的,它确实添加了一个层,但我认为这是值得的。

For example, you might have a use case of "display users that have green eyes".

例如,您可能有一个“显示有绿眼睛的用户”的用例。

with straight JPA:

直接使用 JPA:

List<User> users = entityManager.createQuery("select u  from User u where u.EyeColor = 'green'"");

with a DAO you'd have:

使用 DAO,您将拥有:

List<User> users = dao.UsersWithEyeColor("green");

The DAO here has a couple of advantages:

这里的 DAO 有几个优点:

  1. It is easier to read.
  2. It doesn't expose your database structure to the rest of the application
  3. It would be much easier for unit testing. The class that is getting users with green eyes only needs to create a "Mock" dao. This is easier than mocking JPA.
  1. 阅读起来更容易。
  2. 它不会将您的数据库结构暴露给应用程序的其余部分
  3. 单元测试会容易得多。让用户眼花缭乱的类只需要创建一个“Mock”dao。这比模拟 JPA 更容易。

These are just a few arguments for using a DAO. For a very simple, small application it might be too much overhead. But for anything that will become larger and need to be maintained for many years I think it is worth it.

这些只是使用 DAO 的几个参数。对于一个非常简单的小型应用程序,它的开销可能太大。但是对于任何会变大并且需要维护多年的东西,我认为这是值得的。

回答by Marcelo Tataje

DAO (Data Access Object) is basically a pattern for programming, to use this, you must create a class that will create an object that provides an abstract interface to some type of persistence unit (db, file system. xml, etc).Why is it useful? Because it provides some specific data operations without exposing details of the database.

DAO(数据访问对象)基本上是一种编程模式,要使用它,您必须创建一个类,该类将创建一个对象,该对象为某种类型的持久性单元(db、文件系统、xml 等)提供抽象接口。为什么有用吗?因为它提供了一些特定的数据操作,而不暴露数据库的细节。

An basic example of DAO:

DAO 的一个基本示例:

import java.util.List;


public abstract class DAOFactory {

    public static final int MYSQL_JDBC = 1;
    public static final int MYSQL_JPA = 2;
    public static final int MYSQL_HIBERNATE = 3;

    public abstract List<UserDTO> listAllUsers();

    public static DAOFactory getDAOFactory(int whichFactory) {
        switch (whichFactory) {
        case MYSQL_JDBC : return new MySqlJDBCDaoFactory();
        case MYSQL_JPA: return new MySqlJpaDaoFactory();
        case MYSQL_HIBERNATE: return new MySqlHibernateDaoFactory();
        default: return null;
        }
    }

}

Then you have to create an specific factory for each type of persistence you will manage in your application, and that specific factory must implement the methods you use for persistence, for example listAllUsers();

然后,您必须为将在应用程序中管理的每种类型的持久性创建一个特定的工厂,并且该特定工厂必须实现您用于持久性的方法,例如 listAllUsers();

For example, for MySQL JPA:

例如,对于 MySQL JPA:

public class MySqlJpaDaoFactory extends DAOFactory {

    @Override
    public List<UserDTO> listAllUsers() {
      // Here I implement specific functionality to retrieve data using JPA Framework
        //EntityManagerFactory emf = ...
        //EntityManager em = ...
        //List<UserDTO> list = em.get...();
        //return list;
        return null;
    }

}

For MySQL JDBC you have to do other process:

对于 MySQL JDBC,您必须执行其他过程:

public class MySqlJDBCDaoFactory extends DAOFactory {

    @Override
    public List<UserDTO> listAllUsers() {
        //Connection = DriverManager ...
        //PreparedStatement ps = connection.prepareStatement("select * from ...");
        //ResultSet = ps.executeQuery()
        // and so on...
        return null;
    }

}

Then you invoke your factory this way:

然后你以这种方式调用你的工厂:

DAOFactory myfactory = DAOFactory.getDAOFactory(DAOFactory.MYSQL_JDBC);
List<UserDTO> list = myfactory.listAllUsers();

And if you can see no matter if you change your database framework or persistence mode, you don't have to re-invent the wheel, just change a parameter and you will get the implementation for persistence you want, just based in a parameter.

而且如果你能看到无论你是改变你的数据库框架还是持久化模式,你都不必重新发明轮子,只需要改变一个参数,你就会得到你想要的持久化的实现,仅仅基于一个参数。

Hope it could help you to understand the pattern, I don't use EJB, and if you're using DAO I don't think it is still necessary to implement EJB's.

希望它可以帮助您理解该模式,我不使用 EJB,如果您使用 DAO,我认为仍然没有必要实现 EJB。

Best regards

最好的祝福