Hibernate ORM core functionality - a powerful object/relational mapping solution for Java that implements JPA (Jakarta Persistence API)
Session management in Hibernate Core provides the foundation for all persistence operations through the Session and SessionFactory interfaces. The Session represents a persistence context that manages entity instances and coordinates with the database.
The primary interface for persistence operations, representing a single unit of work and persistence context.
/**
* Main runtime interface for persistence operations.
* Represents a single unit of work and persistence context.
*/
public interface Session extends SharedSessionContract, EntityManager, AutoCloseable {
// Entity lifecycle operations
/**
* Find an entity by primary key
* @param entityClass the entity type
* @param primaryKey the primary key value
* @return the entity instance or null if not found
*/
<T> T find(Class<T> entityClass, Object primaryKey);
/**
* Find an entity by primary key with lock mode
* @param entityClass the entity type
* @param primaryKey the primary key value
* @param lockMode the lock mode to use
* @return the entity instance or null if not found
*/
<T> T find(Class<T> entityClass, Object primaryKey, LockMode lockMode);
/**
* Make a persistent instance persistent
* @param entity the entity instance to persist
*/
void persist(Object entity);
/**
* Copy the state of the given object onto the persistent object
* @param entity the entity to merge
* @return the merged entity instance
*/
<T> T merge(T entity);
/**
* Remove a persistent instance from the datastore
* @param entity the entity instance to remove
*/
void remove(Object entity);
/**
* Re-read the state of the given instance from the underlying database
* @param entity the entity to refresh
*/
void refresh(Object entity);
/**
* Re-read the state of the given instance with the specified lock mode
* @param entity the entity to refresh
* @param lockMode the lock mode to use
*/
void refresh(Object entity, LockMode lockMode);
// Query creation methods
/**
* Create a Query instance for the given HQL/JPQL query string
* @param queryString the HQL/JPQL query string
* @param resultClass the expected result type
* @return Query instance
*/
<R> Query<R> createQuery(String queryString, Class<R> resultClass);
/**
* Create a Query instance for the given HQL/JPQL query string
* @param queryString the HQL/JPQL query string
* @return Query instance returning Object[]
*/
Query<Object[]> createQuery(String queryString);
/**
* Create a NativeQuery instance for the given native SQL query
* @param sqlString the native SQL query string
* @param resultClass the expected result type
* @return NativeQuery instance
*/
<R> NativeQuery<R> createNativeQuery(String sqlString, Class<R> resultClass);
/**
* Create a named query instance
* @param queryName the name of the query
* @param resultClass the expected result type
* @return Query instance
*/
<R> Query<R> createNamedQuery(String queryName, Class<R> resultClass);
// Transaction management
/**
* Begin a resource transaction
* @return the Transaction instance
*/
Transaction beginTransaction();
/**
* Get the current transaction
* @return the current Transaction instance
*/
Transaction getTransaction();
// Session state management
/**
* Force the Session to flush
*/
void flush();
/**
* Completely clear the session
*/
void clear();
/**
* Check if the session is still open
* @return true if session is open
*/
boolean isOpen();
/**
* Check if the session is connected
* @return true if session is connected
*/
boolean isConnected();
// Lock management
/**
* Obtain the specified lock level upon the given object
* @param entity the entity to lock
* @param lockMode the lock mode
*/
void lock(Object entity, LockMode lockMode);
/**
* Obtain the specified lock level upon the given object with timeout
* @param entity the entity to lock
* @param lockOptions lock options including mode and timeout
*/
void lock(Object entity, LockOptions lockOptions);
}Factory for creating Session instances and managing runtime metamodel.
/**
* Factory for Session instances. Usually an application has a single SessionFactory.
* Thread-safe and intended to be shared by all application threads.
*/
public interface SessionFactory extends EntityManagerFactory, AutoCloseable {
/**
* Open a new Session
* @return the created Session
*/
Session openSession();
/**
* Get the current Session bound to the current context
* @return the current Session
* @throws HibernateException if no current session
*/
Session getCurrentSession();
/**
* Obtain a SessionBuilder for creating new sessions
* @return SessionBuilder instance
*/
SessionBuilder withOptions();
/**
* Execute work in a session, automatically managing the session lifecycle
* @param work the work to execute
* @return the result of the work
*/
<R> R inSession(Function<Session, R> work);
/**
* Execute work in a transaction, automatically managing session and transaction lifecycle
* @param work the work to execute
* @return the result of the work
*/
<R> R inTransaction(Function<Session, R> work);
// Metamodel and configuration access
/**
* Get the cache associated with this SessionFactory
* @return the Cache instance
*/
Cache getCache();
/**
* Get the statistics collector for this SessionFactory
* @return the Statistics instance
*/
Statistics getStatistics();
/**
* Check if the SessionFactory is closed
* @return true if closed
*/
boolean isClosed();
/**
* Close the SessionFactory and release resources
*/
void close();
}Builder for creating customized Session instances.
/**
* Builder for Session instances with custom configuration
*/
public interface SessionBuilder {
/**
* Open a session with the configured options
* @return the configured Session
*/
Session openSession();
/**
* Use the specified connection
* @param connection the JDBC connection to use
* @return this SessionBuilder for chaining
*/
SessionBuilder connection(Connection connection);
/**
* Use the specified connection release mode
* @param connectionReleaseMode the connection release mode
* @return this SessionBuilder for chaining
*/
SessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode);
/**
* Should the session built automatically close after completion of each transaction
* @param autoClose true to auto-close
* @return this SessionBuilder for chaining
*/
SessionBuilder autoClose(boolean autoClose);
/**
* Should the session be automatically flushed during completion of each transaction
* @param flushMode the flush mode to use
* @return this SessionBuilder for chaining
*/
SessionBuilder flushMode(FlushMode flushMode);
/**
* Specify the initial CacheMode for the session
* @param cacheMode the cache mode
* @return this SessionBuilder for chaining
*/
SessionBuilder cacheMode(CacheMode cacheMode);
}Session interface for bulk operations without persistence context.
/**
* A stateless session interface for bulk operations.
* No persistence context, no first-level cache, no automatic dirty checking.
*/
public interface StatelessSession extends AutoCloseable {
/**
* Insert an entity
* @param entity the entity to insert
*/
void insert(Object entity);
/**
* Update an entity
* @param entity the entity to update
*/
void update(Object entity);
/**
* Delete an entity
* @param entity the entity to delete
*/
void delete(Object entity);
/**
* Retrieve an entity by id
* @param entityClass the entity type
* @param id the entity id
* @return the entity instance or null
*/
<T> T get(Class<T> entityClass, Object id);
/**
* Create a Query instance
* @param queryString the HQL/JPQL query string
* @param resultClass the expected result type
* @return Query instance
*/
<R> Query<R> createQuery(String queryString, Class<R> resultClass);
/**
* Create a native SQL query
* @param sqlString the native SQL query string
* @param resultClass the expected result type
* @return NativeQuery instance
*/
<R> NativeQuery<R> createNativeQuery(String sqlString, Class<R> resultClass);
/**
* Begin a transaction
* @return the Transaction instance
*/
Transaction beginTransaction();
/**
* Get the current transaction
* @return the current Transaction
*/
Transaction getTransaction();
/**
* Close the stateless session
*/
void close();
}Base contract shared by Session and StatelessSession.
/**
* Base contract for Session and StatelessSession
*/
public interface SharedSessionContract extends AutoCloseable {
/**
* Begin a resource transaction
* @return the Transaction instance
*/
Transaction beginTransaction();
/**
* Get the current transaction
* @return the current Transaction
*/
Transaction getTransaction();
/**
* Create a Query instance
* @param queryString the HQL/JPQL query string
* @return Query instance
*/
Query createQuery(String queryString);
/**
* Create a native SQL query
* @param sqlString the native SQL query string
* @return NativeQuery instance
*/
NativeQuery createNativeQuery(String sqlString);
/**
* Check if the session is open
* @return true if open
*/
boolean isOpen();
/**
* Check if the session is connected
* @return true if connected
*/
boolean isConnected();
/**
* Close the session
*/
void close();
}import org.hibernate.*;
// Opening and using a session
try (Session session = sessionFactory.openSession()) {
Transaction tx = session.beginTransaction();
// Create and persist an entity
User user = new User("john.doe", "John Doe");
session.persist(user);
// Find entity by ID
User foundUser = session.find(User.class, user.getId());
// Update entity
foundUser.setName("Jane Doe");
// No explicit save needed - automatic dirty checking
// Query entities
List<User> users = session.createQuery("FROM User u WHERE u.username LIKE :pattern", User.class)
.setParameter("pattern", "john%")
.getResultList();
tx.commit();
} // Session automatically closed// Execute work in a session
List<User> users = sessionFactory.inSession(session ->
session.createQuery("FROM User", User.class).getResultList()
);
// Execute work in a transaction
User newUser = sessionFactory.inTransaction(session -> {
User user = new User("new.user", "New User");
session.persist(user);
return user;
});try (StatelessSession session = sessionFactory.openStatelessSession()) {
Transaction tx = session.beginTransaction();
// Bulk insert without persistence context overhead
for (int i = 0; i < 10000; i++) {
User user = new User("user" + i, "User " + i);
session.insert(user);
// Periodic flush for large batches
if (i % 100 == 0) {
session.getTransaction().commit();
session.beginTransaction();
}
}
tx.commit();
}Sessions maintain entity state through several mechanisms:
Install with Tessl CLI
npx tessl i tessl/maven-org-hibernate-orm--hibernate-core