Java Hibernate 和 Spring Data JPA 有什么区别

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

What is the difference between Hibernate and Spring Data JPA

javaspringhibernatejpaspring-data-jpa

提问by hard coder

What are the main differences between Hibernate and Spring Data JPA? When should we not use Hibernate or Spring Data JPA? Also, when may Spring JDBC template perform better than Hibernate / Spring Data JPA?

Hibernate 和 Spring Data JPA 之间的主要区别是什么?我们什么时候不应该使用 Hibernate 或 Spring Data JPA?另外,Spring JDBC 模板什么时候比 Hibernate / Spring Data JPA 性能更好?

采纳答案by Vlad Mihalcea

Hibernate is a JPA implementation, while Spring Data JPA is a JPA data access abstraction. Spring Data JPA cannot work without a JPA provider.

Hibernate 是一个 JPA 实现,而 Spring Data JPA 是一个 JPA 数据访问抽象。如果没有 JPA 提供程序,Spring Data JPA 就无法工作。

Spring Data offers a solution to the DDD Repositorypatternor the legacy GenericDaocustom implementations. It can also generate JPA queries on your behalf through method name conventions.

Spring Data 为DDDRepository模式或遗留的GenericDao自定义实现提供了解决方案。它还可以通过方法名称约定代表您生成 JPA 查询。

With Spring Data, you may use Hibernate, Eclipse Link, or any other JPA provider. A very interesting benefit of using Spring or Java EE is that you can control transaction boundaries declaratively using the @Transactionalannotation.

借助 Spring Data,您可以使用 Hibernate、Eclipse Link 或任何其他 JPA 提供程序。使用 Spring 或 Java EE 的一个非常有趣的好处是您可以使用@Transactional注释以声明方式控制事务边界

Spring JDBC is much more lightweight, and it's intended for native querying, and if you only intend to use JDBC alone, then you are better off using Spring JDBC to deal with the JDBC verbosity.

Spring JDBC 更轻量级,它用于本地查询,如果您只想单独使用 JDBC,那么最好使用 Spring JDBC 来处理 JDBC 冗长。

Therefore, Hibernate and Spring Data are complementary rather than competitors.

因此,Hibernate 和 Spring Data 是互补而不是竞争对手。

回答by Bhagwati Malav

There are 3 different things we are using here :

我们在这里使用了 3 种不同的东西:

  1. JPA : Java persistence api which provide specification for persisting, reading, managing data from your java object to relations in database.
  2. Hibernate: There are various provider which implement jpa. Hibernate is one of them. So we have other provider as well. But if using jpa with spring it allows you to switch to different providers in future.
  3. Spring Data JPA : This is another layer on top of jpa which spring provide to make your life easy.
  1. JPA :Java 持久性 API,它提供了从 Java 对象到数据库关系的持久化、读取和管理数据的规范。
  2. Hibernate:有各种实现 jpa 的提供者。Hibernate 就是其中之一。所以我们还有其他供应商。但是如果将 jpa 与 spring 一起使用,它允许您将来切换到不同的提供程序。
  3. Spring Data JPA :这是 jpa 之上的另一个层,spring 提供它使您的生活更轻松。

So lets understand how spring data jpa and spring + hibernateworks-

因此,让我们了解spring 数据 jpa 和 spring + 休眠的工作原理-



Spring Data JPA:

弹簧数据 JPA:

Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.

假设您正在为您的应用程序使用 spring + hibernate。现在您需要有 dao 接口和实现,您将在其中使用 hibernate 的 SessionFactory 编写 crud 操作。假设您正在为 Employee 类编写 dao 类,明天在您的应用程序中,您可能需要为任何其他实体编写类似的 crud 操作。所以我们可以在这里看到很多样板代码。

Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.

现在 Spring data jpa 允许我们通过扩展其存储库(crudrepository,jparepository)来定义 dao 接口,以便它在运行时为您提供 dao 实现。您不再需要编写 dao 实现。这就是 spring data jpa 使您的生活变得轻松的方式。

回答by Klaudiusz Wojtkowiak

I disagree SpringJPA makes live easy. Yes, it provides some classes and you can make some simple DAO fast, but in fact, it's all you can do. If you want to do something more than findById() or save, you must go through hell:

我不同意 SpringJPA 使生活变得轻松。是的,它提供了一些类,您可以快速制作一些简单的 DAO,但实际上,您能做的只有这些。如果你想做的不仅仅是 findById() 或 save ,你必须经历地狱:

  • no EntityManager access in org.springframework.data.repository classes (this is basic JPA class!)
  • own transaction management (hibernate transactions disallowed)
  • huge problems with more than one datasources configuration
  • no datasource pooling (HikariCP must be in use as third party library)
  • 在 org.springframework.data.repository 类中没有 EntityManager 访问(这是基本的 JPA 类!)
  • 自己的事务管理(禁止休眠事务)
  • 多个数据源配置的巨大问题
  • 没有数据源池(HikariCP 必须用作第三方库)

Why own transaction management is an disadvantage? Since Java 1.8 allows default methods into interfaces, Spring annotation based transactions, simple doesn't work.

为什么自己的事务管理是劣势?由于 Java 1.8 允许默认方法进入接口,基于 Spring 注释的事务,简单不起作用。

Unfortunately, SpringJPA is based on reflections, and sometimes you need to point a method name or entity package into annotations (!). That's why any refactoring makes big crash. Sadly, @Transactional works for primary DS only :( So, if you have more than one DataSources, remember - transactions works just for primary one :)

不幸的是,SpringJPA 是基于反射的,有时您需要将方法名称或实体包指向注释(!)。这就是为什么任何重构都会导致大崩溃的原因。遗憾的是,@Transactional 仅适用于主要 DS :( 所以,如果您有多个数据源,请记住 - 事务仅适用于主要数据源 :)

What are the main differences between Hibernate and Spring Data JPA?

Hibernate 和 Spring Data JPA 之间的主要区别是什么?

Hibernate is JPA compatibile, SpringJPA Spring compatibile. Your HibernateJPA DAO can be used with JavaEE or Hibernate Standalone, when SpringJPA can be used within Spring - SpringBoot for example

Hibernate 是 JPA 兼容的,SpringJPA 是 Spring 兼容的。你的 HibernateJPA DAO 可以与 JavaEE 或 Hibernate Standalone 一起使用,当 SpringJPA 可以在 Spring 中使用时 - 例如 SpringBoot

When should we not use Hibernate or Spring Data JPA? Also, when may Spring JDBC template perform better than Hibernate / Spring Data JPA?

我们什么时候不应该使用 Hibernate 或 Spring Data JPA?另外,Spring JDBC 模板什么时候比 Hibernate / Spring Data JPA 性能更好?

Use Spring JDBC only when you need to use much Joins or when you need to use Spring having multiple datasource connections. Generally, avoid JPA for Joins.

仅当您需要使用大量连接或需要使用具有多个数据源连接的 Spring 时才使用 Spring JDBC。通常,避免使用 JPA 进行连接。

But my general advice, use fresh solution—Daobab (http://www.daobab.io). Daobab is my Java and any JPA engine integrator, and I believe it will help much in your tasks :)

但我的一般建议是,使用新的解决方案——Daobab ( http://www.daobab.io)。Daobab 是我的 Java 和任何 JPA 引擎集成商,我相信它会对您的任务有很大帮助:)

回答by Thoopalliamar

Hibernate is implementation of "JPA" which is a specification for Java objects in Database.

Hibernate 是“JPA”的实现,它是数据库中 Java 对象的规范。

I would recommend to use w.r.t JPA as you can switch between different ORMS.

我建议使用 wrt JPA,因为您可以在不同的 ORMS 之间切换。

When you use JDBC then you need to use SQL Queries, so if you are proficient in SQL then go for JDBC.

当你使用 JDBC 时,你需要使用 SQL 查询,所以如果你精通 SQL,那就去 JDBC。

回答by GPopat

If you prefer simplicity and more control on SQL queries then I would suggest going with Spring Data/ Spring JDBC.

如果您更喜欢 SQL 查询的简单性和更多控制,那么我建议您使用 Spring Data/Spring JDBC。

Its good amount of learning curve in JPA and sometimes difficult to debug issues. On the other hand, while you have full control over SQL, it becomes much easier to optimize query and improve performance. You can easily share your SQL with DBA or someone who has a better understanding of Database.

它在 JPA 中的学习曲线很好,有时很难调试问题。另一方面,当您完全控制 SQL 时,优化查询和提高性能变得更加容易。您可以轻松地与 DBA 或对数据库有更深入了解的人共享您的 SQL。

回答by raiks

Spring Datais a convenience library on top of JPAthat abstracts away many things and brings Spring magic (like it or not) to the persistence store access. It is primarily used for working with relational databases. In short, it allows you to declare interfaces that have methods like findByNameOrderByAge(String name);that will be parsed in runtime and converted into appropriate JPAqueries.

Spring Data是一个方便的库,JPA它抽象了许多东西,并将 Spring 的魔力(不管喜欢与否)带到了持久性存储访问中。它主要用于处理关系数据库。简而言之,它允许您声明具有findByNameOrderByAge(String name);将在运行时解析并转换为适当JPA查询的方法的接口。

Its placement atop of JPAmakes its use tempting for:

它位于 的顶部JPA使其具有诱人的用途:

  1. Rookie developers who don't know SQLor know it badly. This is a recipe for disaster but they can get away with it if the project is trivial.

  2. Experienced engineers who know what they do and want to spindle up things fast. This might be a viable strategy (but read further).

  1. 不了解SQL或不了解的菜鸟开发者。这是灾难的秘诀,但如果项目微不足道,他们可以逃脱。

  2. 经验丰富的工程师,他们知道自己在做什么,并希望快速解决问题。这可能是一个可行的策略(但请进一步阅读)。

From my experience with Spring Data, its magic is too much (this is applicable to Springin general). I started to use it heavily in one project and eventually hit several corner cases where I couldn't get the library out of my way and ended up with ugly workarounds. Later I read other users' complaints and realized that these issues are typical for Spring Data. For example, check this issue that led to hours of investigation/swearing:

根据我的经验Spring Data,它的魔力太大了(这适用Spring于一般情况)。我开始在一个项目中大量使用它,最终遇到了几个极端情况,在这些情况下我无法摆脱库,最终得到了丑陋的解决方法。后来我阅读了其他用户的投诉,并意识到这些问题对于Spring Data. 例如,检查这个导致数小时调查/咒骂的问题:

 public TourAccommodationRate createTourAccommodationRate(
        @RequestBody TourAccommodationRate tourAccommodationRate
    ) {
        if (tourAccommodationRate.getId() != null) {
            throw new BadRequestException("id MUST NOT be specified in a body during entry creation");
        }

        // This is an ugly hack required for the Room slim model to work. The problem stems from the fact that
        // when we send a child entity having the many-to-many (M:N) relation to the containing entity, its
        // information is not fetched. As a result, we get NPEs when trying to access all but its Id in the
        // code creating the corresponding slim model. By detaching the entity from the persistence context we
        // force the ORM to re-fetch it from the database instead of taking it from the cache

        tourAccommodationRateRepository.save(tourAccommodationRate);
        entityManager.detach(tourAccommodationRate);
        return tourAccommodationRateRepository.findOne(tourAccommodationRate.getId());
    }

I ended up going lower level and started using JDBI- a nice library with just enough "magic" to save you from the boilerplate. With it, you have complete control over SQL queries and almost never have to fight the library.

我最终降低了级别并开始使用JDBI- 一个不错的库,具有足够的“魔法”,可以将您从样板中拯救出来。有了它,您就可以完全控制 SQL 查询,而且几乎不必与库作斗争。