user3837019
user3837019

Reputation: 221

Are Session and EntityManager the same?

New to JPA and was wondering if Session (Hibernate) and EntityManager are the same thing or not? As both of them basically allow you to manage and search for entities in the relational database.

Also any good source materials on the 2 would be helpful. Thank you in advance!

Upvotes: 5

Views: 1561

Answers (1)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18909

There might be some more slight differences between those 2 but the main concept is the following:

  • Session belongs to org.hibernate package, and is an interface of Hibernate. This belongs to a specific library that provides implementation of JPA, namely hibernate.
  • EntityManager belongs to javax.persistence which belongs to Java EE and not some external library. This is the package that the specifications for JPA are provided from oracle. Every library that wants to implement JPA in java ecosystem must follow these specifications from this package.

If you have Hibernate configured in your project, then for example the entityManager.persist(obj) will invoke the session.persist(obj) through the delegate architecture that hibernate has and then the sessionImpl.persist(obj) of hibernate will be invoked which will do the actual job.

To sum up:

  • session is just an API for Hibernate only.
  • EntityManager is an API provided by Java EE for JPA.

JPA is also implemented by another library eclipselink. In the future a requirement may arise and you may need to switch to use eclipselink library instead of hibernate. This is why you should construct your project to be based on entityManager instead of some library specific API.

Upvotes: 2

Related Questions