361

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 and Spring Data JPA?

2
  • 14
    @NeilStockton asking for a comparison between two technologies isn't asking for opinions. Commented Feb 16, 2018 at 6:03
  • Note to reader: Java Persistence API (JPA) is now known as Jakarta Persistence, one of the dozens of technologies defined as a specification in Jakarta EE. Hibernate ORM implements that spec, as does EclipseLink. Spring is a framework built on top of some of those Jakarta EE technologies. Commented Jan 13 at 17:12

7 Answers 7

471

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

Spring Data offers a solution to the DDD Repository pattern or the legacy GenericDao custom implementations. It can also generate JPA queries on your behalf through method name conventions.

With Spring Data, you may use Hibernate, EclipseLink, 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 @Transactional annotation.

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.

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

Sign up to request clarification or add additional context in comments.

5 Comments

So does this mean that Spring Data JPA cannot exist of itself? That is, under the hood, it uses one of the JPA provider (like Hibernate, Eclipselink or any other JPA provider)?
I mean if I use only hibernate there is little configuration for hibernate level, If I use spring data jpa, that looks much easier than hibernate. In this sense I asked you that question.
More precisely, so far everything works fine you need only to understand the top level i.e. Spring Data JPA. With the first exception you potentially have to know the lower levels i.e. Hibernate, JDBC and the Database.
@CuriousMind No, Spring Data does not exist (work) independently. It uses Hibernate implementation by default, you can notice hibernate-core as one of child deps in spring-data-jpa
In general, separation of implementation and API is good design. In this case Spring data implements idea of repository as an API. This API completely based on repository pattern and do not depends on anything else. Hibernate, eclipse Link or other library provide implementation for Spring Data API. From perspective of developers: spring data is required for compilation phase, hibernate is required for runtime phase.
238

There are 3 different things we are using here :

  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.

So lets understand how spring data jpa and spring + hibernate works-


Spring Data 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.

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.

2 Comments

So what is the Spring Data JPA underlying implementation, is it hibernate?because when i use PagingAndSortingRepository, it show Hibernate logs in the console.
Spring Data JPA used Hibernate implementation by default.. If you see the transitive dependencies of spring-boot-starter-data-jpa, you can see hibernate-core there
42

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:

  • 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)

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

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 :)

What are the main differences between Hibernate and 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

When should we not use Hibernate or Spring Data JPA? Also, when may Spring JDBC template perform better than 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.

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 :)

4 Comments

Daobab, really? If you don't like jpql's like of type safety (I don't), JPA has a type safe criteria API... Standard JPA is better than that poor alternative.
When you use Spring Data JPA there is no reason to need access to EntityManager, so this is not a problem. Spring also makes it very easy to manage transactions declaratively; no need to mess with Hibernate transactions yourself. "Huge problems" with more than one data source: this is not very complicated if you know what you are doing. It is also not true that @Transactional only works for the primary data source. No datasource pooling: I don't know why you think this, but this is simply not true.
\@Transactional killed my last project. I'm reading this because I have to learn it over about ORM in spring boot projects to understand how \@Transactional works. Can't say more because I really DONT understand \@Transactional.
What do you mean by "avoid JPA for Joins"? If I have many Joins, should I use Hibernate instead of Spring Data?
21

Spring Data is a convenience library on top of JPA that 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 JPA queries.

Its placement atop of JPA makes its use tempting for:

  1. Rookie developers who don't know SQL or 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).

From my experience with Spring Data, its magic is too much (this is applicable to Spring in 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:

 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.

4 Comments

this is a good answer but if you could list down the corner cases and detail it further it will be very helpful. It will become a Great Answer. Thanks
Well, it's not that easy to recall those given that I haven't worked with Spring Data for quite a while - I will have to go over the old code and will add more comments. However, one of the annoyances straight from my head - in JPA very often objects have to reference each other (e.g. for cascading operations). This causes a Stack Overflow error (due to circular references) when Spring tries to serialize them forcing you into ugly fiddling/workarounds. This issue is tangential to Spring Data though because it's a JPA issue. However, since JPA is underlying Spring Data you get it "for free".
Edited the post and added one more example.
For lower level needs, you can just use the JPA provider itself if necessary. The amount of boilerplate database code saved with Spring Data JPA is wonderful and for higher level database operations you don't need the verbosity of a Hibernate CriteriaQuery. Why would you write all this extra code if it's not needed?
2

If you prefer simplicity and more control on SQL queries then I would suggest going with 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.

Comments

0

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

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

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

3 Comments

What is w.r.t.?
with respect to
I'm guilty of using WRT sometimes, myself. Your use here doesn't make sense.
-1
  1. JPA

    • JPA is a specification provided by Java to manage relational data in applications.
    • It defines a standard set of APIs and annotations, such as @Entity, @Table, @Id, and the EntityManager interface.
    • However, JPA itself does not provide any implementation; it’s more like a guideline for ORM (Object-Relational Mapping).
    • To use JPA in your application, you need a JPA provider like Hibernate or EclipseLink. Think of JPA as the “rules” that explain what ORM should look like

2. Hibernate

  • Hibernate is a JPA provider and one of the most popular implementations of the JPA specification.
  • While Hibernate follows the rules set by JPA, it also offers additional features that go beyond the standard such as:
    • Caching mechanisms: First-level and second-level caching for optimized performance.
    • Hibernate Query Language (HQL): A powerful query language for database interactions.
    • Custom mappings: Flexible support for mapping complex object structures.
    • Query optimization and Criteria API: For dynamic and efficient query generation.

In many Java projects, Hibernate serves as the engine behind JPA, managing the interaction between the application and the database seamlessly

3. Spring Data JPA

Spring Data JPA is a Spring module that sits on top of JPA to simplify its usage. It provides an abstraction layer that eliminates much of the boilerplate code.

Key Features:

  • Repository Interfaces: Predefined interfaces like CrudRepository and JpaRepository allow you to perform operations (e.g., saving, deleting, querying) with minimal effort.
  • Query Derivation: Automatically implements methods like findByName(String name) based on method naming conventions.
  • Additional Support: Built-in support for pagination, sorting, and auditing

Internally, Spring Data JPA relies on a JPA provider (e.g., Hibernate) to execute these operations, enhancing productivity without compromising flexibility.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.