Interface StatelessSession
- All Superinterfaces:
AutoCloseable, EntityAgent, EntityHandler, Serializable, SharedSessionContract
- All Known Subinterfaces:
StatelessSessionImplementor
Viewed in opposition to Session, the StatelessSession is
a whole competing programming model, one preferred by some developers
for its simplicity and somewhat lower level of abstraction. But the two
kinds of session are not enemies, and may comfortably coexist in a single
program.
A stateless session comes some with designed-in limitations:
- it does not have a first-level cache,
- nor does it implement transactional write-behind or automatic dirty checking.
Furthermore, the basic operations of a stateless session do not have corresponding cascade types, and so an operation performed on one entity via a stateless session never cascades to associated entities.
The basic operations of a stateless session are EntityHandler.get(Class, Object),
insert(Object), update(Object), delete(Object),
and upsert(Object). These operations are always performed
synchronously, resulting in immediate access to the database. Notice that
update is an explicit operation. There is no "flush" operation for a
stateless session, and so modifications to entities are never automatically
detected and made persistent.
Similarly, lazy association fetching is an explicit operation. A collection
or proxy may be fetched by calling fetch(Object).
Stateless sessions are vulnerable to data aliasing effects, due to the lack of a first-level cache.
On the other hand, for certain kinds of transactions, a stateless session may perform slightly faster than a stateful session.
Certain rules applying to stateful sessions are relaxed in a stateless session:
- it's not necessary to discard a stateless session and its entities after an exception is thrown by the stateless session, and
- when an exception is thrown by a stateless session, the current transaction is not automatically marked for rollback.
Since version 7, the configuration property
"hibernate.jdbc.batch_size" has no effect
on a stateless session. Automatic batching may be enabled by explicitly
setting the batch size. However, automatic
batching has the side effect of delaying execution of the batched operation,
thus undermining the synchronous nature of operations performed through a
stateless session. A preferred approach is to explicitly batch operations via
insertMultiple(List), updateMultiple(List), or deleteMultiple(List).
Since version 7, a stateless session makes use of the second-level cache by
default. To bypass the second-level cache, call SharedSessionContract.setCacheMode(CacheMode),
passing CacheMode.IGNORE, or set the configuration properties
"jakarta.persistence.cache.retrieveMode"
and "jakarta.persistence.cache.storeMode"
to BYPASS.
-
Nested Class Summary
Nested classes/interfaces inherited from interface EntityAgent
EntityAgent.CreationOption, EntityAgent.Option -
Method Summary
Modifier and TypeMethodDescriptionvoidDelete a record.voidDelete a record.voiddeleteMultiple(List<?> entities) Delete multiple records in the same order as the entity instances representing the records occur in the given list.<T> Tfetch(T association) Fetch an association or collection that's configured for lazy loading.<T> Tget(EntityGraph<T> graph, GraphSemantic graphSemantic, Object id) Deprecated, for removal: This API element is subject to removal in a future version.<T> Tget(EntityGraph<T> graph, GraphSemantic graphSemantic, Object id, LockMode lockMode) Deprecated, for removal: This API element is subject to removal in a future version.Deprecated, for removal: This API element is subject to removal in a future version.getIdentifier(Object entity) Return the identifier value of the given entity, which may be detached.<T> List<T> getMultiple(EntityGraph<T> entityGraph, GraphSemantic graphSemantic, List<?> ids) Deprecated, for removal: This API element is subject to removal in a future version.voidInsert a record.Insert a record.voidinsertMultiple(List<?> entities) Insert multiple records in the same order as the entity instances representing the new records occur in the given list.voidRefresh the entity instance state from the database.voidRefresh the entity instance state from the database.voidRefresh the entity instance state from the database.voidRefresh the entity instance state from the database.voidUpdate a record.voidUpdate a record.voidupdateMultiple(List<?> entities) Update multiple records in the same order as the entity instances representing the records occur in the given list.voidUse a SQLmerge intostatement to perform an upsert, that is, to insert the record if it does not exist, or update it if it already exists.voidUse a SQLmerge intostatement to perform an upsert.voidupsertMultiple(List<?> entities) Upsert multiple records, that is, for a given record, insert the record if it does not exist or update the record if it already exists, in the same order as the entity instances representing the records occur in the given list.Methods inherited from interface EntityAgent
addOption, getOptions, refresh, refreshMultipleMethods inherited from interface EntityHandler
callWithConnection, find, find, find, findMultiple, findMultiple, get, get, get, getCacheRetrieveMode, getCacheStoreMode, getEntityManagerFactory, getMetamodel, getMultiple, getMultiple, getProperties, runWithConnection, setCacheRetrieveMode, setCacheStoreMode, setProperty, unwrapMethods inherited from interface SharedSessionContract
beginTransaction, close, createEntityGraph, createEntityGraph, createEntityGraph, createMutationQuery, createMutationQuery, createMutationQuery, createNamedMutationQuery, createNamedQuery, createNamedQuery, createNamedQuery, createNamedQuery, createNamedSelectionQuery, createNamedStatement, createNamedStoredProcedureQuery, createNativeMutationQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeQuery, createNativeStatement, createQuery, createQuery, createQuery, createQuery, createQuery, createQuery, createSelectionQuery, createSelectionQuery, createSelectionQuery, createSelectionQuery, createStatement, createStatement, createStatement, createStoredProcedureCall, createStoredProcedureCall, createStoredProcedureCall, createStoredProcedureQuery, createStoredProcedureQuery, createStoredProcedureQuery, disableFilter, doReturningWork, doWork, enableFilter, find, find, fromTransaction, get, get, getCacheMode, getCriteriaBuilder, getEnabledFilter, getEntityGraph, getEntityGraph, getEntityGraphs, getFactory, getJdbcBatchSize, getNamedProcedureCall, getTenantIdentifier, getTenantIdentifierValue, getTransaction, inTransaction, isConnected, isJoinedToTransaction, isOpen, joinTransaction, sessionWithOptions, setCacheMode, setJdbcBatchSize, statelessWithOptions
-
Method Details
-
insert
Insert a record.If the entity
@Idfield is declared to be generated, for example, if it is annotated@GeneratedValue, the id is generated and assigned to the given instance.The
PostPersistcallback will be triggered if the operation is successful.- Specified by:
insertin interfaceEntityAgent- Parameters:
entity- a new transient instance
-
insertMultiple
Insert multiple records in the same order as the entity instances representing the new records occur in the given list.- Specified by:
insertMultiplein interfaceEntityAgent- Parameters:
entities- a list of transient instances to be inserted- Since:
- 7.0
-
insert
Insert a record.The
PostPersistcallback will be triggered if the operation is successful.- Parameters:
entityName- The entityName for the entity to be insertedentity- a new transient instance- Returns:
- the identifier of the instance
-
update
Update a record.The
PostUpdatecallback will be triggered if the operation is successful.- Specified by:
updatein interfaceEntityAgent- Parameters:
entity- a detached entity instance
-
updateMultiple
Update multiple records in the same order as the entity instances representing the records occur in the given list.- Specified by:
updateMultiplein interfaceEntityAgent- Parameters:
entities- a list of detached instances to be updated- Since:
- 7.0
-
update
Update a record.The
PostUpdatecallback will be triggered if the operation is successful.- Parameters:
entityName- The entityName for the entity to be updatedentity- a detached entity instance
-
delete
Delete a record.The
PostRemovecallback will be triggered if the operation is successful.- Specified by:
deletein interfaceEntityAgent- Parameters:
entity- a detached entity instance
-
deleteMultiple
Delete multiple records in the same order as the entity instances representing the records occur in the given list.- Specified by:
deleteMultiplein interfaceEntityAgent- Parameters:
entities- a list of detached instances to be deleted- Since:
- 7.0
-
delete
Delete a record.The
PostRemovecallback will be triggered if the operation is successful.- Parameters:
entityName- The entity name for the entity to be deletedentity- a detached entity instance
-
upsert
Use a SQLmerge intostatement to perform an upsert, that is, to insert the record if it does not exist, or update it if it already exists.This method never performs id generation, and does not accept an entity instance with a null identifier. When id generation is required, use
insert(Object).On the other hand,
upsert()does accept an entity instance with an assigned identifier value, even if the entity@Idfield is declared to be generated, for example, if it is annotated@GeneratedValue. Thus, this method may be used to import data from an external source.- Specified by:
upsertin interfaceEntityAgent- Parameters:
entity- a detached entity instance, or a new instance with an assigned identifier- Throws:
TransientObjectException- if the entity has a null id- Since:
- 6.3
-
upsertMultiple
Upsert multiple records, that is, for a given record, insert the record if it does not exist or update the record if it already exists, in the same order as the entity instances representing the records occur in the given list.- Specified by:
upsertMultiplein interfaceEntityAgent- Parameters:
entities- a list of detached instances and new instances with assigned identifiers- Since:
- 7.0
-
upsert
Use a SQLmerge intostatement to perform an upsert.- Parameters:
entityName- The entity name for the entity to be mergedentity- a detached entity instance- Throws:
TransientObjectException- if the entity has a null id- Since:
- 6.3
-
get
@Nonnull @Deprecated(forRemoval=true, since="8.0") Object get(@Nonnull String entityName, @Nonnull Object id, @Nonnull LockMode lockMode) Deprecated, for removal: This API element is subject to removal in a future version.Retrieve a record, obtaining the specified lock mode.- Parameters:
entityName- The name of the entity to retrieveid- The id of the entity to retrievelockMode- The lock mode to apply to the entity- Returns:
- a detached entity instance, or null if there is no instance with the given id
-
get
@Nonnull @Deprecated(forRemoval=true, since="8.0") <T> T get(@Nonnull EntityGraph<T> graph, @Nonnull GraphSemantic graphSemantic, @Nonnull Object id) Deprecated, for removal: This API element is subject to removal in a future version.Retrieve a record, fetching associations specified by the givenEntityGraph.- Parameters:
graph- TheEntityGraphgraphSemantic- aGraphSemanticspecifying how the graph should be interpretedid- The id of the entity to retrieve- Returns:
- a detached entity instance, or null if there is no instance with the given id
- Since:
- 6.3
-
get
@Nonnull @Deprecated(forRemoval=true, since="8.0") <T> T get(@Nonnull EntityGraph<T> graph, @Nonnull GraphSemantic graphSemantic, @Nonnull Object id, @Nonnull LockMode lockMode) Deprecated, for removal: This API element is subject to removal in a future version.Retrieve a record, fetching associations specified by the givenEntityGraph, and obtaining the specified lock mode.- Parameters:
graph- TheEntityGraphgraphSemantic- aGraphSemanticspecifying how the graph should be interpretedid- The id of the entity to retrievelockMode- The lock mode to apply to the entity- Returns:
- a detached entity instance, or null if there is no instance with the given id
- Since:
- 6.3
-
getMultiple
@Nonnull @Deprecated(forRemoval=true, since="8.0") <T> List<T> getMultiple(@Nonnull EntityGraph<T> entityGraph, @Nonnull GraphSemantic graphSemantic, @Nonnull List<?> ids) Deprecated, for removal: This API element is subject to removal in a future version.Retrieve multiple rows, returning instances of the root entity of the givenEntityGraphwith the fetched associations specified by the graph, in a list where the position of an instance in the list matches the position of its identifier in the given array, and the list contains a null value if there is no persistent instance matching a given identifier.- Parameters:
entityGraph- TheEntityGraphgraphSemantic- aGraphSemanticspecifying how the graph should be interpretedids- The ids of the entities to retrieve- Returns:
- an ordered list of detached entity instances, with null elements representing missing entities
- Since:
- 7.0
-
refresh
Refresh the entity instance state from the database.- Specified by:
refreshin interfaceEntityAgent- Parameters:
entity- The entity to be refreshed.
-
refresh
-
refresh
-
refresh
-
fetch
Fetch an association or collection that's configured for lazy loading.Book book = session.get(Book.class, isbn); // book is immediately detached session.fetch(book.getAuthors()); // fetch the associated authors book.getAuthors().forEach(author -> ... ); // iterate the collection
Warning: this operation in a stateless session is quite sensitive to data aliasing effects and should be used with great care. It's usually better to fetch associations using eager join fetching.
- Specified by:
fetchin interfaceEntityAgent- Parameters:
association- a lazy-loaded association- Since:
- 6.0
- See Also:
-
getIdentifier
-
EntityHandler.get(EntityGraph, Object, FindOption...)instead