Interface Session


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.

  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Starts a transaction for this session.
    void
    Detaches every entity and discards all unflushed changes.
    void
    Rolls back any active transaction, detaches entities, and releases session resources.
    void
    Flushes pending changes and commits the active transaction.
    boolean
    contains(Object entity)
    Tests whether this session manages an entity that is not scheduled for removal.
    long
    count(Object entity, String field)
    Counts 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.
    void
    Creates missing tables, indexes, and constraints for registered mappings.
    void
    detach(Object entity)
    Stops tracking an instance, discarding its unflushed changes.
    <T> T
    find(Class<T> type, Object id)
    Finds an entity, reusing its managed instance when present.
    <T> T
    find(Class<T> type, Object id, LockMode mode)
    Finds an entity and optionally locks its database row.
    void
    Writes pending inserts, updates, relationship changes, and removals.
    <T> boolean
    increment(Class<T> type, Object id, String field, long amount)
    Atomically adds to an integral counter in SQL after flushing pending changes.
    void
    initialize(Object entity, String field)
    Loads a relationship if it is still uninitialized.
    boolean
    isLoaded(Object entity, String field)
    Checks relationship initialization without fetching its contents.
    boolean
    Reports whether a transaction failure prevents committing.
    boolean
    Reports whether this session has an active transaction.
    void
    lock(Object entity, LockMode mode)
    Applies a lock mode to a managed entity's row.
    <T> T
    merge(T entity)
    Copies state into a managed instance, cascading through MERGE associations.
    <T> void
    persist(T entity)
    Makes a new entity managed and schedules its insertion at flush.
    <T> Query<T>
    query(Class<T> type)
    Creates a fluent entity query.
    void
    refresh(Object entity)
    Reloads a persisted managed instance, discarding its local changes.
    void
    remove(Object entity)
    Schedules a managed entity for deletion, cascading REMOVE associations.
    void
    Rolls back the active transaction and detaches all managed entities.
    void
    Checks mapped columns, type families, nullability, and primary keys.
  • Method Details

    • createQuery

      <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.
      Type Parameters:
      T - result type
      Parameters:
      statement - query using entity and Java attribute names
      resultType - expected entity or scalar type; use Object[].class for tuples
      Returns:
      a query belonging to this session
      Throws:
      IllegalArgumentException - if syntax or a mapped name is unsupported
    • createQuery

      JpqlQuery<Object> createQuery(String statement)
      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

      boolean contains(Object entity)
      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

      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 - 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

      <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.
      Type Parameters:
      T - entity type
      Parameters:
      type - mapped entity class
      id - non-null scalar key, embedded key, or composite Identifier
      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

      <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.
      Type Parameters:
      T - entity type
      Parameters:
      type - mapped entity class
      id - entity identifier
      mode - requested lock mode
      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

      void lock(Object entity, LockMode mode)
      Applies a lock mode to a managed entity's row.
      Parameters:
      entity - managed instance
      mode - 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

      <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

      void remove(Object entity)
      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

      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 - 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 elsewhere
      PersistenceException - if no usable transaction is active or a write fails
    • increment

      <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.
      Type Parameters:
      T - entity type
      Parameters:
      type - mapped entity class
      id - entity identifier
      field - Java name of an int or long field that is neither key nor version
      amount - 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 counter
      PersistenceException - if no usable transaction is active or the update fails
    • query

      <T> Query<T> query(Class<T> type)
      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

      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 - owner with a persisted identifier
      field - Java name of the relationship or element collection
      Returns:
      relationship size; zero or one for a to-one association
    • isLoaded

      boolean isLoaded(Object entity, String field)
      Checks relationship initialization without fetching its contents.
      Parameters:
      entity - mapped instance
      field - Java relationship name
      Returns:
      true if loaded or if the instance has no managed lazy state
    • initialize

      void initialize(Object entity, String field)
      Loads a relationship if it is still uninitialized.
      Parameters:
      entity - relationship owner
      field - Java relationship name
      Throws:
      LazyInitializationException - if unloaded state belongs to a detached entity
      PersistenceException - if the session is closed or fetching fails