为什么使用 JPA 而不是直接在 Java File 上写 SQL 查询(即直接写到 JDBC)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4406310/
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-08-14 17:05:29  来源:igfitidea点击:

Why use JPA instead of directly writing SQL query on Java File (i.e. directly to JDBC)?

javadatabaseormjpa

提问by Meow

I've been reading up on several articles what is JPA (Java Persistent API)and which vendor supporting it (DataNucleus, JBoss Hibernate etc)

我一直在阅读几篇文章是什么JPA (Java Persistent API)以及支持它的供应商(DataNucleus、JBoss Hibernate 等)

I don't have experience with ORM (object relational mapping).

我没有 ORM(对象关系映射)的经验。

What I have done so far is to write my own Database classes using DTO and DAO. So far I'm happy about what I have but would like to know why people use JPA over Java file which contains SQL.

到目前为止,我所做的是使用 DTO 和 DAO 编写自己的数据库类。到目前为止,我对我所拥有的感到高兴,但想知道为什么人们使用 JPA 而不是包含 SQL 的 Java 文件

To me I feel like writing DAO class would be ok something like below.

对我来说,我觉得编写 DAO 类应该可以,如下所示。

public class DAOUsers {
     public void insertNewUser(DTO DtoUser) {
           String query = "INSERT INTO users(username, address) " +
                          "VALUES(DtoUser.username , DtoUser.address)";
           Executor.run(query);
     }

}

I've learned JPA uses JPQL, Java persistent query language and it operates against entity object rather than directly with db tables.

我了解到 JPA 使用 JPQL、Java 持久查询语言,它针对实体对象而不是直接使用 db 表进行操作。

My understanding (correct me if Im wrong) is that entity object here is same as my DTO object (kind of like bean?)

我的理解(如果我错了请纠正我)这里的实体对象与我的 DTO 对象相同(有点像 bean?)

But anyhow.. what really benefit JPA gives over writing pure SQL in my file? Seems like using annotations required by JPA and make SQL not readable feels not really attractive to me..

但无论如何.. JPA 比在我的文件中编写纯 SQL 真正有什么好处?似乎使用 JPA 所需的注释并使 SQL 不可读感觉对我来说不是很有吸引力..

please let me know if you need more clarification, I'm new to this topic and would like to hear some opinion.

如果您需要更多说明,请告诉我,我是这个话题的新手,想听听一些意见。

采纳答案by Vineet Reynolds

Why use JPA instead of directly writing SQL query on Java File (i.e. directly to JDBC) ?

为什么使用 JPA 而不是直接在 Java 文件上编写 SQL 查询(即直接到 JDBC)?

Certain projects require engineers to focus more on the object model rather than on the actual SQL queries used to access data stores. The question can actually be interpreted as

某些项目要求工程师更多地关注对象模型,而不是用于访问数据存储的实际 SQL 查询。这个问题实际上可以解释为

Why should one use an ORM framework ?

为什么要使用 ORM 框架?

which can have different answers in different contexts.

在不同的上下文中可以有不同的答案。

Most projects can benefit from having a domain model, with persistence being a second concern. With JPA (implementations) or most other ORM frameworks, it is possible to have all entities i.e. tables in your database, modelled as classes in Java. Additionally, it also possible to embed behavior into these classes and therefore achieve a behaviorally rich domain model. The entities in this model can have multiple purposes, including the purpose of replacing DTOs for transporting data across tiers.

大多数项目都可以从域模型中受益,持久性是第二个问题。使用 JPA(实现)或大多数其他 ORM 框架,可以将所有实体(即数据库中的表)都建模为 Java 中的类。此外,还可以将行为嵌入到这些类中,从而实现行为丰富的领域模型。此模型中的实体可以有多种用途,包括替换 DTO 以跨层传输数据的目的。

That said, there are places where ORM frameworks may not be a direct fit to the problem, especially when the data model is already established, or when one is working with legacy systems where mapping database tables to Java classes is a non-trivial exercise. And in certain cases, if one needs to absolutely tune the heck out of the SQL generated by the ORM framework, then ORM frameworks are usually a bad fit.

也就是说,有些地方 ORM 框架可能无法直接解决这个问题,尤其是当数据模型已经建立时,或者当一个人使用遗留系统时,将数据库表映射到 Java 类是一项非常重要的工作。在某些情况下,如果需要完全调整 ORM 框架生成的 SQL,那么 ORM 框架通常不适合。

Related Questions

相关问题

  1. Java EE Architecture - Are DAO's still recommended when using an ORM like JPA 2?
  2. Using an ORM or plain SQL?
  3. ORM vs Handcoded Data Access Layer
  1. Java EE 架构 - 在使用像 JPA 2 这样的 ORM 时是否仍然推荐 DAO?
  2. 使用 ORM 还是普通 SQL?
  3. ORM 与手工编码的数据访问层

回答by javamonkey79

If done correctly, you can map SQL queries directly to java objects with JPA implementations such as hibernate. I recently did a project where I had a POJO and 3 or 4 annotations and little bit of setup code to take a stored procedure and map it directly to a list of objects (of the POJO class type). This to me is part of the power of JPA.

如果操作正确,您可以使用 Hibernate 等 JPA 实现将 SQL 查询直接映射到 java 对象。我最近做了一个项目,我有一个 POJO 和 3 或 4 个注释和一点点设置代码来获取存储过程并将其直接映射到对象列表(POJO 类类型)。这对我来说是 JPA 力量的一部分。

If you're using it like you would straight up SQL+JDBC then I don't know of any advantages.

如果您像直接使用 SQL+JDBC 一样使用它,那么我不知道有什么优势。

There is a decent article hereon the advantages of JPA.

有一个像样的文章在这里对JPA的优势。

Hope this helps.

希望这可以帮助。

回答by Ravi Parmar

As we all know that object is one of most import thing of our life and in programming object is very easy way to simplify any problem.... and if object is available there then why we use whole thing instead of that small part of that thing means object....

众所周知,对象是我们生活中最重要的东西之一,在编程中对象是简化任何问题的非常简单的方法……如果对象在那里可用,那么为什么我们使用整个事物而不是其中的一小部分东西的意思是对象....

  • if you're hand-coding SQL statements in your enterprise application, you are spending a significant amount of your development time updating and maintaining your persistence layer.
  • 如果您在企业应用程序中手动编写 SQL 语句,您将花费大量的开发时间来更新和维护持久层。

In persistance,==> no more need of JDBC APIs for result set or data handling. ==>It helps reduce the lines of code, &&&&&& ==>It abstracts our application away from the underlying SQL database and sql dialect. Switching to other SQL database requires few changes in Hibernate configuration file (Write once / run-anywhere).

在持久性方面,==> 结果集或数据处理不再需要 JDBC API。==>它有助于减少代码行数,&&&&&& ==>它将我们的应用程序从底层 SQL 数据库和 sql 方言中抽象出来。切换到其他 SQL 数据库需要对 Hibernate 配置文件进行少量更改(一次写入/随处运行)。

回答by Stephen C

What really benefit JPA gives over writing pure SQL in my file?

与在我的文件中编写纯 SQL 相比,JPA 有什么真正的好处?

Here are some of the benefits:

以下是一些好处:

  • JPA allows you to avoid writing DDL in a database specific dialect of SQL. Instead you write "mappings" in XML, or using Java annotations.

  • JPA allows you to avoid writing DML in the database specific dialect of SQL.

  • JPA allows you to load and save Java objects and graphs without any DML language at all.

  • When you doneed to perform queries JPQL allows you to express the queries in terms of the Java entities rather than the (native) SQL tables and columns.

  • JPA 允许您避免使用特定于数据库的 SQL 方言编写 DDL。相反,您用 XML 或使用 Java 注释编写“映射”。

  • JPA 允许您避免在 SQL 的数据库特定方言中编写 DML。

  • JPA 允许您在完全不使用任何 DML 语言的情况下加载和保存 Java 对象和图形。

  • 当您确实需要执行查询时,JPQL 允许您根据 Java 实体而不是(本机)SQL 表和列来表达查询。

Generally speaking, JPA is simpler, cleaner and less labour intensive than JDBC + SQL + hand-written mappings. The more complicated your data model, the more beneficial it is.

一般来说,JPA 比 JDBC + SQL + 手写映射更简单、更干净、劳动强度更低。你的数据模型越复杂,它就越有益。

However, if performance is an overridingconcern, JPA does tend to get in the way by adding layers between your application and the database. If your application requires you to extensively hand-optimize the native database queries and schemas to maximize performance, JPA is probably not a good fit.

但是,如果性能是最重要的问题,那么 JPA 确实会通过在应用程序和数据库之间添加层来妨碍。如果您的应用程序需要您大量手动优化本机数据库查询和模式以最大限度地提高性能,那么 JPA 可能不适合。

JPA is probably also not for you if you are much more comfortablejuggling Java, JDBC and SQL in the same application, than with letting the ORM deal with the messy details. (But if you are, you are probably in the minority ...)

如果您愿意在同一个应用程序中处理 Java、JDBC 和 SQL,而不是让 ORM 处理凌乱的细节,那么 JPA 可能也不适合您。(但如果你是,你可能是少数......)

回答by yetAnotherSE

In addition, as you know Java's slogan: "Write once, run everywhere"

另外,如你所知Java的口号:“一次编写,到处运行”

Also with JPQL you can execute your JPQL queries on every database (DB2, Oracle, etc..)

同样使用 JPQL,您可以在每个数据库(DB2、Oracle 等)上执行 JPQL 查询。

回答by Doctor Eval

Although this is an old question, I feel like it deserves a new answer. I'm a late adopter of JPA, I've been using it on and off for a couple of years, and while I've had my moments of being impressed by the simplicity of standing up a new application, I have become decidedly unimpressed with the performance, complexity and learning curve required to do JPA correctly. The answers in this thread actually reinforce my position.

虽然这是一个老问题,但我觉得它值得一个新的答案。我是 JPA 的较晚采用者,我已经断断续续地使用它几年了,虽然我曾对建立新应用程序的简单性印象深刻,但我已经完全不为所动具有正确执行 JPA 所需的性能、复杂性和学习曲线。这个帖子中的答案实际上加强了我的立场。

Firstly, @vineet suggests "the entities can have multiple purposes"... which I've seen in production and I'd say is encouraged by ORM. So much for cohesion and the single responsibility principal. In my experience, adding behaviours to database entities is asking for trouble. I know this because I've done it, and lived to regret it.

首先,@vineet 建议“实体可以有多种用途”......我在生产中看到过,我会说 ORM 鼓励这样做。凝聚力和单一职责主体就到此为止。根据我的经验,向数据库实体添加行为是自找麻烦。我知道这一点,因为我已经做到了,而且我一直在后悔。

Second, there are simple alternatives to the complexity of JPA that provide the ability to use classes with a RDBMS without all the heaviness (and performance issues) caused by the mismatch that ORM tries (unsuccessfully) to solve. We've been using non-JPA relational-class mapping tools for a decade in an application with over 1,000 tables and we simply do not see how JPA is an improvement over more direct access to the database. JPA obscures the power of the database while adding overhead (in the form of annotations and JQL) to the class model... shouldn't it work the other way?

其次,对于 JPA 的复杂性,有一些简单的替代方案,它提供了将类与 RDBMS 一起使用的能力,而不会因 ORM 尝试(未成功)解决的不匹配而导致的所有繁重(和性能问题)。十年来,我们一直在具有 1,000 多个表的应用程序中使用非 JPA 关系类映射工具,但我们根本看不到 JPA 是如何改进对更直接访问数据库的方式。JPA 在向类模型添加开销(以注释和 JQL 的形式)的同时掩盖了数据库的功能......它不应该以另一种方式工作吗?

@water suggests numerous things which are true in theory but impractical in reality. For example, having switched backend databases three times I can assure readers that there is no such thing as a few config tweaks and you're done. I'd suggest, if you're spending a lot of time maintaining your persistence layer, your database model is evolving, and you'd be doing the same or more work in JPA. Particularly when non trivial queries in JPA require the use of JQL!

@water 暗示了许多理论上正确但实际上不切实际的事情。例如,切换后端数据库 3 次后,我可以向读者保证,没有一些配置调整之类的事情,您就大功告成了。我建议,如果您花费大量时间维护持久层,那么您的数据库模型正在发展,并且您将在 JPA 中做相同或更多的工作。特别是当 JPA 中的非平凡查询需要使用 JQL 时!

Almost everyone pretends that JPA developers don't need to know SQL. What I've seen in practice is that now we have to learn SQL andJQL. Apparently we don't have to do DDL - but in any non trivial application of courseyou need to know DDL. Hibernate doesn't even recommend using automatic DDL generation. Apparently we don't have to do DML, except when we call out to a Native Query, which of course is non-portable, smashes the cache, and has all the same problems as JDBC...

几乎每个人都假装 JPA 开发人员不需要了解 SQL。我在实践中看到的是,现在我们必须学习 SQLJQL。显然我们不必做 DDL——但在任何非平凡的应用程序中当然需要知道 DDL。Hibernate 甚至不建议使用自动 DDL 生成。显然我们不必做 DML,除非我们调用 Native Query,这当然是不可移植的,会破坏缓存,并且具有与 JDBC 相同的所有问题......

Ultimately, in a properly structured application where the domain model is independent from the business logic, JPA provides little in the way of functionality for what I've found to be a very high learning curve - because the domain model is actually very easy to build. I wouldn't use JDBC directly, but something like Apache DBUtils provides a simple layer above JDBC that maps rows to objects, and with a bit of effort can provide most of the advantages of JPA with none of the hiding and none of the overhead.

最终,在域模型独立于业务逻辑的结构合理的应用程序中,JPA 几乎没有为我发现非常高的学习曲线提供功能 - 因为域模型实际上很容易构建. 我不会直接使用 JDBC,但是像 Apache DBUtils 这样的东西在 JDBC 之上提供了一个简单的层,将行映射到对象,并且只需付出一点努力就可以提供 JPA 的大部分优点,没有任何隐藏和开销。

I've been developing Java database applications since JDBC 1.0, using a variety of libraries (and iODBC and ESQL before JDBC), and for performance reasons alone, I'm done with JPA. But even if performance was better, the learning curve and incomplete abstractions give me serious pause. JPA is complex and tries to hide details which, in my opinion, developers actually need to care about. As an example, we recently saw hibernate issue 250 delete commands to the database when one would suffice. JPA, by its nature, makes this kind of error easy.

自 JDBC 1.0 以来,我一直在开发 Java 数据库应用程序,使用各种库(以及 JDBC 之前的 iODBC 和 ESQL),仅出于性能原因,我已经完成了 JPA。但即使性能更好,学习曲线和不完整的抽象也让我严重停顿。JPA 很复杂,并试图隐藏在我看来开发人员实际上需要关心的细节。例如,我们最近看到 hibernate 在足够的情况下向数据库发出 250 个删除命令。JPA 就其性质而言,使这种错误变得容易。

I'm not advocating for JDBC, I'm simply advocating against JPA. Developers who don't or can't work in SQL probably shouldn't be writing relational applications - any more than Developers like me, who couldn't do matrix algebra to save my life, should be writing 3D games. Developers who do use SQL for a living should be horrified by the contorted SQL that hibernate, for one, sends to the server, in order to avoid round trips that shouldn't be necessary in the first place.

我不是在提倡 JDBC,我只是在提倡反对 JPA。不会或不能使用 SQL 的开发人员可能不应该编写关系应用程序 - 就像像我这样无法通过矩阵代数来挽救我生命的开发人员应该编写 3D 游戏一样。确实以 SQL 为生的开发人员应该对那些在休眠状态下发送到服务器的扭曲 SQL 感到震惊,以避免一开始就不必要的往返。

回答by Shreyu

  • JPA is a perfect fit for non performance oriented complex applications.
  • JDBC is a best fit where performance is a key performer.
  • JPA 非常适合非面向性能的复杂应用程序。
  • JDBC 最适合在性能是关键执行者的情况下。