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.
-
Method Summary
Modifier and TypeMethodDescriptionvoidStarts a transaction for this session.voidclear()Detaches every entity and discards all unflushed changes.voidclose()Rolls back any active transaction, detaches entities, and releases session resources.voidFlushes pending changes and commits the active transaction.booleanTests whether this session manages an entity that is not scheduled for removal.longCounts stored related rows without loading the relationship's entities.createQuery(String statement) Creates an untyped JPQL query, including bulk update or delete statements.<T> JpqlQuery<T> createQuery(String statement, Class<T> resultType) Creates a typed query using the supported JPQL subset.voidCreates missing tables, indexes, and constraints for registered mappings.voidStops tracking an instance, discarding its unflushed changes.<T> TFinds an entity, reusing its managed instance when present.<T> TFinds an entity and optionally locks its database row.voidflush()Writes pending inserts, updates, relationship changes, and removals.<T> booleanAtomically adds to an integral counter in SQL after flushing pending changes.voidinitialize(Object entity, String field) Loads a relationship if it is still uninitialized.booleanChecks relationship initialization without fetching its contents.booleanReports whether a transaction failure prevents committing.booleanReports whether this session has an active transaction.voidApplies a lock mode to a managed entity's row.<T> Tmerge(T entity) Copies state into a managed instance, cascading through MERGE associations.<T> voidpersist(T entity) Makes a new entity managed and schedules its insertion at flush.<T> Query<T> Creates a fluent entity query.voidReloads a persisted managed instance, discarding its local changes.voidSchedules a managed entity for deletion, cascading REMOVE associations.voidRolls back the active transaction and detaches all managed entities.voidChecks mapped columns, type families, nullability, and primary keys.
-
Method Details
-
createQuery
Creates a typed query using the supported JPQL subset. Parsing and mapping validation occur immediately, before SQL execution.- Type Parameters:
T- result type- Parameters:
statement- query using entity and Java attribute namesresultType- expected entity or scalar type; useObject[].classfor tuples- Returns:
- a query belonging to this session
- Throws:
IllegalArgumentException- if syntax or a mapped name is unsupported
-
createQuery
Creates an untyped JPQL query, including bulk update or delete statements.- Parameters:
statement- 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
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
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
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
boolean isTransactionActive()Reports whether this session has an active transaction.- Returns:
- true between a successful begin and commit or rollback
-
isRollbackOnly
boolean isRollbackOnly()Reports whether a transaction failure prevents committing.- Returns:
- true when the active transaction must be rolled back
-
contains
Tests whether this session manages an entity that is not scheduled for removal.- Parameters:
entity- instance to test; null is allowed- Returns:
- true if the instance is currently managed and not removed
-
detach
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- instance to detach
-
clear
void clear()Detaches every entity and discards all unflushed changes. Does not end the transaction or undo SQL already executed in it. -
close
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
Finds an entity, reusing its managed instance when present. An uncached lookup flushes pending changes in an active transaction.- Type Parameters:
T- entity type- Parameters:
type- mapped entity classid- non-null scalar key, embedded key, or compositeIdentifier- Returns:
- the managed entity, or null if no matching row exists
- Throws:
IllegalArgumentException- if the identifier shape is invalidPersistenceException- if no generated mapping exists for the entity type
-
find
Finds an entity and optionally locks its database row. A pessimistic lock requires an active transaction and a supporting backend.- Type Parameters:
T- entity type- Parameters:
type- mapped entity classid- entity identifiermode- requested lock mode- Returns:
- the managed entity, or null if no matching row exists
- Throws:
UnsupportedOperationException- if the database does not support row locksOptimisticLockException- if a managed version is stalePersistenceException- if the required transaction is not active
-
lock
Applies a lock mode to a managed entity's row.- Parameters:
entity- managed instancemode- requested lock mode; pessimistic modes require an active transaction- Throws:
UnsupportedOperationException- if the database does not support row locksOptimisticLockException- if the row is missing or its version is stalePersistenceException- if the entity is not managed or a transaction is required
-
persist
<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.- Type Parameters:
T- entity type- Parameters:
entity- new mapped instance- Throws:
PersistenceException- if no transaction is active or the instance cannot be persisted
-
merge
<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.- Type Parameters:
T- entity type- Parameters:
entity- new or detached mapped instance- Returns:
- the managed instance containing the merged state
- Throws:
PersistenceException- if no transaction is active or merging fails
-
remove
Schedules a managed entity for deletion, cascading REMOVE associations.- Parameters:
entity- managed instance to remove- Throws:
PersistenceException- if no transaction is active or the instance is not managed
-
refresh
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- persisted instance managed by this session- Throws:
PersistenceException- if the instance cannot be refreshed
-
flush
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 elsewherePersistenceException- if no usable transaction is active or a write fails
-
increment
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.- Type Parameters:
T- entity type- Parameters:
type- mapped entity classid- entity identifierfield- Java name of an int or long field that is neither key nor versionamount- signed amount to add- Returns:
- true if a row changed; false for a missing row, null counter, or overflow
- Throws:
IllegalArgumentException- if the field is not a supported counterPersistenceException- if no usable transaction is active or the update fails
-
query
Creates a fluent entity query.- Type Parameters:
T- entity type- Parameters:
type- mapped entity class- Returns:
- an initially unrestricted query
- Throws:
PersistenceException- if no generated mapping exists for the entity type
-
createTables
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
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
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- owner with a persisted identifierfield- Java name of the relationship or element collection- Returns:
- relationship size; zero or one for a to-one association
-
isLoaded
-
initialize
Loads a relationship if it is still uninitialized.- Parameters:
entity- relationship ownerfield- Java relationship name- Throws:
LazyInitializationException- if unloaded state belongs to a detached entityPersistenceException- if the session is closed or fetching fails
-