Reputation: 272
what is the difference between spring data save
and hibernate save
? Do they work in same way?
Upvotes: 6
Views: 2179
Reputation: 207026
You'll understand this better if you understand exactly what the relationship is between JPA, Hibernate and Spring Data JPA.
JPA (Java Persistence API) is a standard interface specification for doing ORM (object-relational mapping) in Java. Note that it does not by itself implement the interface. You need a library that implements the JPA specification to be able to use it in your software.
Hibernate is an implementation of JPA - it's a library that implements the JPA specification.
Spring Data JPA is a subproject of the Spring Framework, which makes it easier to work with JPA and integrate it into the rest of the Spring Framework.
If you use Spring Data JPA, you also need to have an implementation of JPA in your project, such as Hibernate.
You use the interfaces and classes that Spring Data JPA provides, and it talks to the underlying JPA implementation (Hibernate) to actually talk to the database.
Saving an entity through Spring Data JPA will ultimately call Hibernate to save the entity, so in the end the effect is the same.
However: If you are using Spring Data JPA, you should not be using Hibernate directly. In fact, you should not have any direct references at all to Hibernate in your own code. By directly using Hibernate in your code you would be bypassing Spring Data JPA entirely.
Upvotes: 8
Reputation: 692231
Hibernate's Session.save()
is a proprietary Hibernate operation that doesn't exist in JPA. It basically does the same thing as EntityManager.persist()
, except it guarantees that the ID is generated and returns it. The same cascades are not applied though, since Hibernate has a proprietary SAVE cascade option that of course does exist in JPA.
Spring-data-jpa's SimpleJpaRepository's save operation either calls EntityManager.persist()
, if the entity is considered new, or EntityManager.merge()
, if the entity is not considered new.
So no, they're not the same thing, and don't work the same way.
Upvotes: 6