Basics Flashcards
Java EE specs to Jakarta Persistence
Starting Hibernate 6, the default JPA provider packages have been moved from javax.* to jakarta.*
JPA vs Hibernate
Think of JPA as the guidelines/specification that must be followed or an interface, while Hibernate’s JPA implementation is code that meets the API as defined by JPA and provides the under the hood functionality.
The benefit of this is that we can swap out hibernates implementation of JPA for another implementation of the JPA specification.
SessionFactory
SessionFactory in Hibernate is a key component in managing the database connections and sessions for an application. It acts as a factory for creating and managing Session objects, which are the main interfaces for interacting with the database.
You typically configure SessionFactory via an XML file (hibernate.cfg.xml) or through programmatic configuration using Configuration in Java.
Or, with Hibernate’s newer approach, using ServiceRegistry:
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
SessionFactory Responsibilities
Creates Session instances
Handles optional second-level caching, which helps in reducing database access for frequently accessed data.
Manages and optimizes database connections, reducing the overhead of establishing new connections.
Coordinates transaction management through the Session objects it provides.
The SessionFactory should be closed at the application shutdown to release any database connections and resources.
sessionFactory.close();
Hibernate Lifecycle
Transient State
When we instantiate an object of a POJO class using the new operator then the object is in the transient state. This object is not connected with any hibernate session.
Persistent State
Persist entity into database
Detached State
Removed State