A Comparison Between JPA and JDBC – JPA和JDBC之间的比较

最后修改: 2021年 6月 22日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’re going to look at the differences between the Java Database Connectivity (JDBC) API and the Java Persistence API (JPA).

在本教程中,我们将了解Java数据库连接(JDBC)APIJava持久性API(JPA)之间的区别。

2. What Is JDBC

2.什么是JDBC

JDBC is a programming-level interface for Java applications that communicate with a database. An application uses this API to communicate with a JDBC manager. It’s the common API that our application code uses to communicate with the database. Beyond the API is the vendor-supplied, JDBC-compliant driver for the database we’re using.

JDBC是一个编程级别的接口,用于与数据库通信的Java应用程序。一个应用程序使用这个API与JDBC管理器进行通信。它是我们的应用程序代码用来与数据库通信的通用API。在API之外,是供应商提供的、符合JDBC标准的驱动程序,用于我们正在使用的数据库。

3. What Is JPA

3.什么是JPA

JPA is a Java standard that allows us to bind Java objects to records in a relational database. It’s one possible approach to Object Relationship Mapping(ORM), allowing the developer to retrieve, store, update, and delete data in a relational database using Java objects. Several implementations are available for the JPA specification.

JPA是一项Java标准,它允许我们将Java对象与关系数据库中的记录进行绑定。 它是对象关系映射(ORM)的一种可能方法,允许开发人员使用Java对象在关系数据库中检索、存储、更新和删除数据。有几种实现可用于JPA规范。

4. JPA vs JDBC

4.JPA vs JDBC

When it comes to deciding how to communicate with back-end database systems, software architects face a significant technological challenge. The debate between JPA and JDBC is often the deciding factor, as the two database technologies take very different approaches to work with persistent data. Let’s analyze the key differences between them.

在决定如何与后端数据库系统通信时,软件架构师面临着重大的技术挑战。JPA和JDBC之间的争论往往是决定性因素,因为这两种数据库技术采取了非常不同的方法来处理持久性数据。让我们分析一下它们之间的关键区别。

4.1. Database Interactions

4.1.数据库的相互作用

JDBC allows us to write SQL commands to read data from and update data to a relational database. JPA, unlike JDBC, allows developers to construct database-driven Java programs utilizing object-oriented semantics. The JPA annotations describe how a given Java class and its variables map to a given table and its columns in a database.

JDBC允许我们编写SQL命令,从关系型数据库中读取数据并更新数据。JPA与JDBC不同,它允许开发人员利用面向对象的语义来构建数据库驱动的Java程序。JPA注释描述了一个给定的Java类及其变量如何映射到数据库中给定的表及其列

Let’s see how we can map an Employee class to an employee database table:

让我们看看如何将一个Employee类映射到一个employee数据库表:

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
    @Column(name = "employee_name")
    private String employeeName;
}

The JPA framework then handles all the time-consuming, error-prone coding required to convert between object-oriented Java code and the back-end database

然后JPA框架处理所有耗时、易出错的编码,这些编码需要在面向对象的Java代码和后端数据库之间进行转换

4.2. Managing Associations

4.2.管理关联

When associating database tables in a query with JDBC, we need to write out the full SQL query, while with JPA, we simply use annotations to create one-to-one, one-to-many, many-to-one, and many-to-many associations.

当用JDBC在查询中关联数据库表时,我们需要写出完整的SQL查询,而用JPA,我们只需使用注释来创建一对一、一对多、多对一和多对多的关联

Let’s say our employee table has a one-to-many relationship with the communication table:

假设我们的employee表与communication表有一个一对多的关系。

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
 
    @OneToMany(mappedBy = "employee", fetch = FetchType.EAGER)
    @OrderBy("firstName asc")
    private Set communications;
}

The owner of this relationship is Communication, so we’re using the mappedBy attribute in Employee to make it a bi-directional relationship.

这个关系的所有者是Communication,所以我们在Employee中使用mappedBy属性,使它成为双向关系。

4.3. Database Dependency

4.3.数据库依赖性

JDBC is database-dependent, which means that different scripts must be written for different databases. On the other side, JPA is database-agnostic, meaning that the same code can be used in a variety of databases with few (or no) modifications.

JDBC是依赖于数据库的。这意味着不同的脚本必须被编写针对不同的数据库在另一方面,JPA是数据库无关的,意味着相同的代码可以被用于各种数据库,只需进行少量(或没有)修改

4.4. Exception Handling

4.4.异常处理

Because JDBC throws checked exceptions, such as SQLException, we must write it in a try-catch block. On the other hand, the JPA framework uses only unchecked exceptions, like Hibernate. Hence, we don’t need to catch or declare them at every place we’re using them.

因为JDBC会抛出检查过的异常,例如SQLException,我们必须将其写入try-catch块中。另一方面,JPA框架只使用未检查的异常,像Hibernate。因此,我们不需要在每个使用它们的地方捕捉或声明它们。

4.5. Performance

4.5.业绩

The difference between JPA and JDBC is essentially who does the coding: the JPA framework or a local developer. Either way, we’ll have to deal with the object-relation impedance mismatch.

JPA和JDBC之间的区别本质上是由谁来进行编码:JPA框架还是本地开发人员。无论是哪种方式,我们都必须处理对象关系的阻抗不匹配

To be fair, when we write SQL queries incorrectly, JDBC performance can be abysmally sluggish. When deciding between the two technologies, performance shouldn’t be a point of dispute. Professional developers are more than capable of producing Java applications that run equally well regardless of the technology utilized.

公平地说,当我们错误地编写SQL查询时,JDBC的性能可能会低得令人发指。在决定这两种技术时,性能不应该是一个争议点。专业的开发人员完全有能力制作出同样运行良好的Java应用程序,而不用考虑所使用的技术。

4.6. JDBC Dependency

4.6.JDBC的依赖性

JPA-based applications still use JDBC under the hood. Therefore, when we utilize JPA, our code is actually using the JDBC APIs for all database interactions. In other words, JPA serves as a layer of abstraction that hides the low-level JDBC calls from the developer, making database programming considerably easier.

基于JPA的应用程序仍然在后台使用JDBC。因此,当我们利用JPA时,我们的代码实际上是在使用JDBC API进行所有的数据库交互。换句话说,JPA作为一个抽象层,向开发者隐藏了低级别的JDBC调用,使数据库编程变得相当容易

4.7. Transaction Management

4.7.事务管理

In JDBC, transaction management is handled explicitly by using commit and rollback. On the other hand, transaction management is implicitly provided in JPA.

在JDBC中,事务管理是通过使用提交和回滚来明确处理的。另一方面,交易管理在JPA中是隐式提供的

5. Pros and Cons

5.优点和缺点

The most obvious benefit of JDBC over JPA is that it’s simpler to understand. On the other side, if a developer doesn’t grasp the internal workings of the JPA framework or database design, they will be unable to write good code.

与JPA相比,JDBC最明显的好处是它更容易理解另一方面,如果开发人员没有掌握JPA框架或数据库设计的内部工作原理,他们将无法写出好的代码

Also, JPA is thought to be better suited for more sophisticated applications by many developers. But, JDBC is considered the preferable alternative if an application will use a simple database and we don’t plan to migrate it to a different database vendor.

另外,JPA被许多开发人员认为更适合于更复杂的应用。但是,JDBC 被认为是最好的选择,如果一个应用程序将使用一个简单的数据库,并且我们不打算将其迁移到一个不同的数据库供应商

The main advantage of JPA over JDBC for developers is that they can code their Java applications using object-oriented principles and best practices without having to worry about database semantics. As a result, development can be completed more quickly, especially when software developers lack a solid understanding of SQL and relational databases.

对于开发人员来说,JPA相对于JDBC的主要优势在于,他们可以使用面向对象的原则和最佳实践来编码他们的Java应用程序,而不必担心数据库语义的问题。因此,开发可以更快完成,特别是当软件开发人员缺乏对SQL和关系型数据库的扎实了解时

Also, because a well-tested and robust framework is handling the interaction between the database and the Java application, we should see a decrease in errors from the database mapping layer when using JPA.

此外,由于一个经过良好测试的强大框架正在处理数据库和Java应用程序之间的交互,我们应该看到在使用JPA时,数据库映射层的错误会减少。

6. Conclusion

6.结论

In this quick tutorial, we explored the key differences between JPA and JDBC.

在这个快速教程中,我们探讨了JPA和JDBC的主要区别。

While JPA brings many advantages, we have many other high-quality alternatives to use if JPA doesn’t work best for our current application requirements.

虽然JPA带来了很多优势,但如果JPA不能最好地满足我们当前的应用需求,我们还有很多其他高质量的替代方案可以使用。