Hibernate, as an ORM solution, effectively "sits between" the Java application data access layer and the Relational Database, as can be seen in the diagram above.
The Java application makes use of the Hibernate APIs to load, store, query, etc its domain data.
The below diagram shows important interfaces and classes of Hibernate framework:
- SessionFactory (org.hibernate.SessionFactory)
- SessionFactory is a thread-safe (and immutable) representation of the mapping of the application domain model to a database.
- SessionFactory acts as a factory for org.hibernate.Session instances. So the EntityManagerFactory is the JPA equivalent of a SessionFactory and basically, those two converge into the same SessionFactory implementation.
- A SessionFactory is very expensive to create, so, for any given database, the application should have only one associated SessionFactory.
- The SessionFactory maintains services that Hibernate uses across all Session(s) such as second-level caches, connection pools, transaction system integrations, etc.
- Session (org.hibernate.Session)
- The Session is a single-threaded, short-lived object conceptually modeling a "Unit of Work". In JPA nomenclature, the Sessionis represented by an EntityManager.
- Behind the scenes, the Hibernate Session wraps a JDBC java.sql.Connection and acts as a factory for org.hibernate.Transaction instances. It maintains a generally "repeatable read" persistence context (first level cache) of the application domain model.
Transaction (org.hibernate.Transaction)
The Transaction is a single-threaded, short-lived object used by the application to demarcate individual physical transaction boundaries. The EntityTransaction is the JPA equivalent and both act as an abstraction API to isolate the application from the underlying transaction system in use (JDBC or JTA).