public interface Session

A persistence context obtained from an entity manager’s openSession() method. Tracks changes to managed entities and maintains one instance per entity identity. Sessions and their queries are not thread-safe; use and complete transactions on one thread. Call close() when finished; it never commits pending work.

Writes require an explicit transaction. Queries flush pending changes when a transaction is active. A failed flush marks that transaction rollback-only; call rollbackTransaction() before continuing. Rollback detaches all entities but does not restore the Java objects’ previous field values.

Lazy relationships require an open session that still manages their owner. Load relationships before detaching or serializing if they are needed later. Implementations are supplied by the ORM; applications should not implement this interface.

Methods

public abstract <T> JpqlQuery<T> createQuery(String statement, Class<T> resultType)Creates a typed query using the supported JPQL subset.
public abstract JpqlQuery<Object> createQuery(String statement)Creates an untyped JPQL query, including bulk update or delete statements.
public abstract void beginTransaction()Starts a transaction for this session.
public abstract void commitTransaction()Flushes pending changes and commits the active transaction.
public abstract void rollbackTransaction()Rolls back the active transaction and detaches all managed entities.
public abstract boolean isTransactionActive()Reports whether this session has an active transaction.
public abstract boolean isRollbackOnly()Reports whether a transaction failure prevents committing.
public abstract boolean contains(Object entity)Tests whether this session manages an entity that is not scheduled for removal.
public abstract void detach(Object entity)Stops tracking an instance, discarding its unflushed changes.
public abstract void clear()Detaches every entity and discards all unflushed changes.
public abstract void close()Rolls back any active transaction, detaches entities, and releases session resources.
public abstract <T> T find(Class<T> type, Object id)Finds an entity, reusing its managed instance when present.
public abstract <T> T find(Class<T> type, Object id, LockMode mode)Finds an entity and optionally locks its database row.
public abstract void lock(Object entity, LockMode mode)Applies a lock mode to a managed entity’s row.
public abstract <T> void persist(T entity)Makes a new entity managed and schedules its insertion at flush.
public abstract <T> T merge(T entity)Copies state into a managed instance, cascading through MERGE associations.
public abstract void remove(Object entity)Schedules a managed entity for deletion, cascading REMOVE associations.
public abstract void refresh(Object entity)Reloads a persisted managed instance, discarding its local changes.
public abstract void flush()Writes pending inserts, updates, relationship changes, and removals.
public abstract <T> boolean increment(Class<T> type, Object id, String field, long amount)Atomically adds to an integral counter in SQL after flushing pending changes.
public abstract <T> Query<T> query(Class<T> type)Creates a fluent entity query.
public abstract void createTables()Creates missing tables, indexes, and constraints for registered mappings.
public abstract void validateSchema()Checks mapped columns, type families, nullability, and primary keys.
public abstract long count(Object entity, String field)Counts stored related rows without loading the relationship’s entities.
public abstract boolean isLoaded(Object entity, String field)Checks relationship initialization without fetching its contents.
public abstract void initialize(Object entity, String field)Loads a relationship if it is still uninitialized.

Method details

createQuery

public abstract <T> JpqlQuery<T> createQuery(String statement, Class<T> resultType)
Creates a typed query using the supported JPQL subset. Parsing and mapping validation occur immediately, before SQL execution.

Parameters

statement String
query using entity and Java attribute names
resultType Class<T>
expected entity or scalar type; use Object[].class for tuples
<T>
result type

Returns

a query belonging to this session

Throws

IllegalArgumentException
if syntax or a mapped name is unsupported

createQuery

public abstract JpqlQuery<Object> createQuery(String statement)
Creates an untyped JPQL query, including bulk update or delete statements.

Parameters

statement String
query using entity and Java attribute names

Returns

a query yielding entities, scalars, or Object[] tuples

Throws

IllegalArgumentException
if syntax or a mapped name is unsupported

beginTransaction

public abstract void beginTransaction()
Starts a transaction for this session.

Throws

PersistenceException
if the session is closed, a transaction is already active, or the database cannot begin the transaction

commitTransaction

public abstract void commitTransaction()
Flushes pending changes and commits the active transaction. A failure leaves a still-active database transaction requiring rollback. If the database already ended the failed transaction, the session detaches its entities and becomes inactive; a new transaction can then be started.

Throws

PersistenceException
if no usable transaction is active or commit fails

rollbackTransaction

public abstract void rollbackTransaction()
Rolls back the active transaction and detaches all managed entities. Pending changes are discarded; Java field values are not reverted.

Throws

PersistenceException
if no transaction is active or rollback fails

isTransactionActive

public abstract boolean isTransactionActive()
Reports whether this session has an active transaction.

Returns

true between a successful begin and commit or rollback

isRollbackOnly

public abstract boolean isRollbackOnly()
Reports whether a transaction failure prevents committing.

Returns

true when the active transaction must be rolled back

contains

public abstract boolean contains(Object entity)
Tests whether this session manages an entity that is not scheduled for removal.

Parameters

entity Object
instance to test; null is allowed

Returns

true if the instance is currently managed and not removed

detach

public abstract void detach(Object entity)
Stops tracking an instance, discarding its unflushed changes. Cascades DETACH only through already loaded relationships. Does nothing for an instance that is not managed by this session.

Parameters

entity Object
instance to detach

clear

public abstract void clear()
Detaches every entity and discards all unflushed changes. Does not end the transaction or undo SQL already executed in it.

close

public abstract void close()
Rolls back any active transaction, detaches entities, and releases session resources. Repeated calls have no effect. The entity manager retains ownership of its database.

Throws

PersistenceException
if rollback or resource release fails

find

public abstract <T> T find(Class<T> type, Object id)
Finds an entity, reusing its managed instance when present. An uncached lookup flushes pending changes in an active transaction.

Parameters

type Class<T>
mapped entity class
id Object
non-null scalar key, embedded key, or composite Identifier
<T>
entity type

Returns

the managed entity, or null if no matching row exists

Throws

IllegalArgumentException
if the identifier shape is invalid
PersistenceException
if no generated mapping exists for the entity type

find

public abstract <T> T find(Class<T> type, Object id, LockMode mode)
Finds an entity and optionally locks its database row. A pessimistic lock requires an active transaction and a supporting backend.

Parameters

type Class<T>
mapped entity class
id Object
entity identifier
mode LockMode
requested lock mode
<T>
entity type

Returns

the managed entity, or null if no matching row exists

Throws

UnsupportedOperationException
if the database does not support row locks
OptimisticLockException
if a managed version is stale
PersistenceException
if the required transaction is not active

lock

public abstract void lock(Object entity, LockMode mode)
Applies a lock mode to a managed entity’s row.

Parameters

entity Object
managed instance
mode LockMode
requested lock mode; pessimistic modes require an active transaction

Throws

UnsupportedOperationException
if the database does not support row locks
OptimisticLockException
if the row is missing or its version is stale
PersistenceException
if the entity is not managed or a transaction is required

persist

public abstract <T> void persist(T entity)
Makes a new entity managed and schedules its insertion at flush. Traverses associations with PERSIST cascade. A to-one reference to an unsaved entity without that cascade is rejected at flush.

Parameters

entity T
new mapped instance
<T>
entity type

Throws

PersistenceException
if no transaction is active or the instance cannot be persisted

merge

public abstract <T> T merge(T entity)
Copies state into a managed instance, cascading through MERGE associations. Continue working with the returned instance; the supplied detached instance does not become managed merely because it was passed to this method.

Parameters

entity T
new or detached mapped instance
<T>
entity type

Returns

the managed instance containing the merged state

Throws

PersistenceException
if no transaction is active or merging fails

remove

public abstract void remove(Object entity)
Schedules a managed entity for deletion, cascading REMOVE associations.

Parameters

entity Object
managed instance to remove

Throws

PersistenceException
if no transaction is active or the instance is not managed

refresh

public abstract void refresh(Object entity)
Reloads a persisted managed instance, discarding its local changes. Traverses REFRESH cascades. Rejects new, unflushed instances before changing session state. A failure after reload begins clears the context and marks an active transaction rollback-only.

Parameters

entity Object
persisted instance managed by this session

Throws

PersistenceException
if the instance cannot be refreshed

flush

public abstract void flush()
Writes pending inserts, updates, relationship changes, and removals. Does not commit. Failure marks the active transaction rollback-only.

Throws

OptimisticLockException
if a versioned row was changed or removed elsewhere
PersistenceException
if no usable transaction is active or a write fails

increment

public abstract <T> boolean increment(Class<T> type, Object id, String field, long amount)
Atomically adds to an integral counter in SQL after flushing pending changes. Also increments an optimistic version when present and refreshes a managed instance of the affected row. Guards against counter and version overflow.

Parameters

type Class<T>
mapped entity class
id Object
entity identifier
field String
Java name of an int or long field that is neither key nor version
amount long
signed amount to add
<T>
entity type

Returns

true if a row changed; false for a missing row, null counter, or overflow

Throws

IllegalArgumentException
if the field is not a supported counter
PersistenceException
if no usable transaction is active or the update fails

query

public abstract <T> Query<T> query(Class<T> type)
Creates a fluent entity query.

Parameters

type Class<T>
mapped entity class
<T>
entity type

Returns

an initially unrestricted query

Throws

PersistenceException
if no generated mapping exists for the entity type

createTables

public abstract void createTables()
Creates missing tables, indexes, and constraints for registered mappings. Run outside application transactions. Does not migrate existing tables.

Throws

PersistenceException
if a transaction is active or schema creation fails

validateSchema

public abstract void validateSchema()
Checks mapped columns, type families, nullability, and primary keys. Does not migrate the schema or exhaustively validate indexes and foreign keys.

Throws

PersistenceException
if a mapped table or column is incompatible or inaccessible

count

public abstract long count(Object entity, String field)
Counts stored related rows without loading the relationship’s entities. Flushes pending changes when a transaction is active. Detached owners are identified by their persisted key; local detached relationship edits are ignored.

Parameters

entity Object
owner with a persisted identifier
field String
Java name of the relationship or element collection

Returns

relationship size; zero or one for a to-one association

isLoaded

public abstract boolean isLoaded(Object entity, String field)
Checks relationship initialization without fetching its contents.

Parameters

entity Object
mapped instance
field String
Java relationship name

Returns

true if loaded or if the instance has no managed lazy state

initialize

public abstract void initialize(Object entity, String field)
Loads a relationship if it is still uninitialized.

Parameters

entity Object
relationship owner
field String
Java relationship name

Throws

LazyInitializationException
if unloaded state belongs to a detached entity
PersistenceException
if the session is closed or fetching fails