Top Description Inners Fields Constructors Methods
org.springframework.orm.jpa

public abstract Class EntityManagerFactoryUtils

extends Object
Class Inheritance
Imports
java.util.Map, jakarta.persistence.EntityExistsException, .EntityManager, .EntityManagerFactory, .EntityNotFoundException, .LockTimeoutException, .NoResultException, .NonUniqueResultException, .OptimisticLockException, .PersistenceException, .PessimisticLockException, .Query, .QueryTimeoutException, .SynchronizationType, .TransactionRequiredException, org.apache.commons.logging.Log, .LogFactory, org.springframework.beans.factory.BeanFactoryUtils, .ListableBeanFactory, .NoSuchBeanDefinitionException, org.springframework.core.Ordered, org.springframework.dao.CannotAcquireLockException, .DataAccessException, .DataAccessResourceFailureException, .DataIntegrityViolationException, .EmptyResultDataAccessException, .IncorrectResultSizeDataAccessException, .InvalidDataAccessApiUsageException, .PessimisticLockingFailureException, org.springframework.jdbc.datasource.DataSourceUtils, org.springframework.lang.Nullable, org.springframework.transaction.support.ResourceHolderSynchronization, .TransactionSynchronizationManager, org.springframework.util.Assert, .CollectionUtils, .StringUtils

Helper class featuring methods for JPA EntityManager handling, allowing for reuse of EntityManager instances within transactions. Also provides support for exception translation.

Mainly intended for internal use within the framework.

Author
Juergen Hoeller
Since
2.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
EntityManagerFactoryUtils.TransactionalEntityManagerSynchronization

Callback for resource cleanup at the end of a non-JPA transaction (e.g. when participating in a JtaTransactionManager transaction), fully synchronized with the ongoing transaction.

private static class
EntityManagerFactoryUtils.TransactionScopedEntityManagerSynchronization

Minimal callback that just closes the EntityManager at the end of the transaction.

Field Summary

Modifier and TypeField and Description
public static final int
ENTITY_MANAGER_SYNCHRONIZATION_ORDER

Order value for TransactionSynchronization objects that clean up JPA EntityManagers.

private static final Log

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public static void
applyTransactionTimeout(Query
the JPA Query object
query
,
EntityManagerFactory
the JPA EntityManagerFactory that the Query was created for
emf
)

Apply the current transaction timeout, if any, to the given JPA Query object.

private static void
cleanupTransaction(Object
arbitrary object that holds transaction data, if any (as returned by prepareTransaction)
transactionData
,
EntityManagerFactory
the EntityManagerFactory that the EntityManager has been created with
emf
)

Prepare a transaction on the given EntityManager, if possible.

public static void
closeEntityManager(EntityManager
the JPA EntityManager to close (may be null)
em
)

Close the given JPA EntityManager, catching and logging any cleanup exceptions thrown.

public static DataAccessException

Returns:

the corresponding DataAccessException instance, or null if the exception should not be translated
convertJpaAccessExceptionIfPossible
(RuntimeException
runtime exception that occurred
ex
)

Convert the given runtime exception to an appropriate exception from the org.springframework.dao hierarchy.

public static EntityManager

Returns:

the EntityManager, or null if none found
doGetTransactionalEntityManager
(EntityManagerFactory
the EntityManagerFactory to create the EntityManager with
emf
,
Map<?, ?>
the properties to be passed into the createEntityManager call (may be null)
properties
)

Obtain a JPA EntityManager from the given factory.

public static EntityManager

Returns:

the EntityManager, or null if none found
doGetTransactionalEntityManager
(EntityManagerFactory
the EntityManagerFactory to create the EntityManager with
emf
,
Map<?, ?>
the properties to be passed into the createEntityManager call (may be null)
properties
,
boolean
whether to automatically join ongoing transactions (according to the JPA 2.1 SynchronizationType rules)
synchronizedWithTransaction
)

Obtain a JPA EntityManager from the given factory.

public static EntityManagerFactory

Returns:

the EntityManagerFactory
findEntityManagerFactory
(ListableBeanFactory
the ListableBeanFactory to search
beanFactory
,
String
the name of the persistence unit (may be null or empty, in which case a single bean of type EntityManagerFactory will be searched for)
unitName
)

Find an EntityManagerFactory with the given name in the given Spring application context (represented as ListableBeanFactory).

public static EntityManager

Returns:

the EntityManager, or null if none found
getTransactionalEntityManager
(EntityManagerFactory
the EntityManagerFactory to create the EntityManager with
emf
)

Obtain a JPA EntityManager from the given factory.

public static EntityManager

Returns:

the EntityManager, or null if none found
getTransactionalEntityManager
(EntityManagerFactory
the EntityManagerFactory to create the EntityManager with
emf
,
Map<?, ?>
the properties to be passed into the createEntityManager call (may be null)
properties
)

Obtain a JPA EntityManager from the given factory.

private static Object

Returns:

an arbitrary object that holds transaction data, if any (to be passed into cleanupTransaction)
prepareTransaction
(EntityManager
the EntityManager to prepare
em
,
EntityManagerFactory
the EntityManagerFactory that the EntityManager has been created with
emf
)

Prepare a transaction on the given EntityManager, if possible.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

ENTITY_MANAGER_SYNCHRONIZATION_ORDERback to summary
public static final int ENTITY_MANAGER_SYNCHRONIZATION_ORDER

Order value for TransactionSynchronization objects that clean up JPA EntityManagers. Return DataSourceUtils.CONNECTION_SYNCHRONIZATION_ORDER - 100 to execute EntityManager cleanup before JDBC Connection cleanup, if any.

See Also
org.springframework.jdbc.datasource.DataSourceUtils#CONNECTION_SYNCHRONIZATION_ORDER
loggerback to summary
private static final Log logger

Constructor Detail

EntityManagerFactoryUtilsback to summary
public EntityManagerFactoryUtils()

Method Detail

applyTransactionTimeoutback to summary
public static void applyTransactionTimeout(Query query, EntityManagerFactory emf)

Apply the current transaction timeout, if any, to the given JPA Query object.

This method sets the JPA query hint "jakarta.persistence.query.timeout" accordingly.

Parameters
query:Query

the JPA Query object

emf:EntityManagerFactory

the JPA EntityManagerFactory that the Query was created for

cleanupTransactionback to summary
private static void cleanupTransaction(Object transactionData, EntityManagerFactory emf)

Prepare a transaction on the given EntityManager, if possible.

Parameters
transactionData:Object

arbitrary object that holds transaction data, if any (as returned by prepareTransaction)

emf:EntityManagerFactory

the EntityManagerFactory that the EntityManager has been created with

See Also
JpaDialect#cleanupTransaction
closeEntityManagerback to summary
public static void closeEntityManager(EntityManager em)

Close the given JPA EntityManager, catching and logging any cleanup exceptions thrown.

Parameters
em:EntityManager

the JPA EntityManager to close (may be null)

See Also
jakarta.persistence.EntityManager#close()
convertJpaAccessExceptionIfPossibleback to summary
public static DataAccessException convertJpaAccessExceptionIfPossible(RuntimeException ex)

Convert the given runtime exception to an appropriate exception from the org.springframework.dao hierarchy. Return null if no translation is appropriate: any other exception may have resulted from user code, and should not be translated.

The most important cases like object not found or optimistic locking failure are covered here. For more fine-granular conversion, JpaTransactionManager etc support sophisticated translation of exceptions via a JpaDialect.

Parameters
ex:RuntimeException

runtime exception that occurred

Returns:DataAccessException

the corresponding DataAccessException instance, or null if the exception should not be translated

Annotations
@Nullable
doGetTransactionalEntityManagerback to summary
public static EntityManager doGetTransactionalEntityManager(EntityManagerFactory emf, Map<?, ?> properties) throws PersistenceException

Obtain a JPA EntityManager from the given factory. Is aware of a corresponding EntityManager bound to the current thread, e.g. when using JpaTransactionManager.

Same as getEntityManager, but throwing the original PersistenceException.

Parameters
emf:EntityManagerFactory

the EntityManagerFactory to create the EntityManager with

properties:Map<?, ?>

the properties to be passed into the createEntityManager call (may be null)

Returns:EntityManager

the EntityManager, or null if none found

Annotations
@Nullable
Exceptions
PersistenceException:
if the EntityManager couldn't be created
See Also
getTransactionalEntityManager(jakarta.persistence.EntityManagerFactory), JpaTransactionManager
doGetTransactionalEntityManagerback to summary
public static EntityManager doGetTransactionalEntityManager(EntityManagerFactory emf, Map<?, ?> properties, boolean synchronizedWithTransaction) throws PersistenceException

Obtain a JPA EntityManager from the given factory. Is aware of a corresponding EntityManager bound to the current thread, e.g. when using JpaTransactionManager.

Same as getEntityManager, but throwing the original PersistenceException.

Parameters
emf:EntityManagerFactory

the EntityManagerFactory to create the EntityManager with

properties:Map<?, ?>

the properties to be passed into the createEntityManager call (may be null)

synchronizedWithTransaction:boolean

whether to automatically join ongoing transactions (according to the JPA 2.1 SynchronizationType rules)

Returns:EntityManager

the EntityManager, or null if none found

Annotations
@Nullable
Exceptions
PersistenceException:
if the EntityManager couldn't be created
See Also
getTransactionalEntityManager(jakarta.persistence.EntityManagerFactory), JpaTransactionManager
findEntityManagerFactoryback to summary
public static EntityManagerFactory findEntityManagerFactory(ListableBeanFactory beanFactory, String unitName) throws NoSuchBeanDefinitionException

Find an EntityManagerFactory with the given name in the given Spring application context (represented as ListableBeanFactory).

The specified unit name will be matched against the configured persistence unit, provided that a discovered EntityManagerFactory implements the EntityManagerFactoryInfo interface. If not, the persistence unit name will be matched against the Spring bean name, assuming that the EntityManagerFactory bean names follow that convention.

If no unit name has been given, this method will search for a default EntityManagerFactory through ListableBeanFactory#getBean(Class).

Parameters
beanFactory:ListableBeanFactory

the ListableBeanFactory to search

unitName:String

the name of the persistence unit (may be null or empty, in which case a single bean of type EntityManagerFactory will be searched for)

Returns:EntityManagerFactory

the EntityManagerFactory

Exceptions
NoSuchBeanDefinitionException:
if there is no such EntityManagerFactory in the context
See Also
EntityManagerFactoryInfo#getPersistenceUnitName()
getTransactionalEntityManagerback to summary
public static EntityManager getTransactionalEntityManager(EntityManagerFactory emf) throws DataAccessResourceFailureException

Obtain a JPA EntityManager from the given factory. Is aware of a corresponding EntityManager bound to the current thread, e.g. when using JpaTransactionManager.

Note

Will return null if no thread-bound EntityManager found!

Parameters
emf:EntityManagerFactory

the EntityManagerFactory to create the EntityManager with

Returns:EntityManager

the EntityManager, or null if none found

Annotations
@Nullable
Exceptions
DataAccessResourceFailureException:
if the EntityManager couldn't be obtained
See Also
JpaTransactionManager
getTransactionalEntityManagerback to summary
public static EntityManager getTransactionalEntityManager(EntityManagerFactory emf, Map<?, ?> properties) throws DataAccessResourceFailureException

Obtain a JPA EntityManager from the given factory. Is aware of a corresponding EntityManager bound to the current thread, e.g. when using JpaTransactionManager.

Note

Will return null if no thread-bound EntityManager found!

Parameters
emf:EntityManagerFactory

the EntityManagerFactory to create the EntityManager with

properties:Map<?, ?>

the properties to be passed into the createEntityManager call (may be null)

Returns:EntityManager

the EntityManager, or null if none found

Annotations
@Nullable
Exceptions
DataAccessResourceFailureException:
if the EntityManager couldn't be obtained
See Also
JpaTransactionManager
prepareTransactionback to summary
private static Object prepareTransaction(EntityManager em, EntityManagerFactory emf)

Prepare a transaction on the given EntityManager, if possible.

Parameters
em:EntityManager

the EntityManager to prepare

emf:EntityManagerFactory

the EntityManagerFactory that the EntityManager has been created with

Returns:Object

an arbitrary object that holds transaction data, if any (to be passed into cleanupTransaction)

Annotations
@Nullable
See Also
JpaDialect#prepareTransaction
org.springframework.orm.jpa back to summary

private Class EntityManagerFactoryUtils.TransactionalEntityManagerSynchronization

extends ResourceHolderSynchronization<EntityManagerHolder, EntityManagerFactory>
implements Ordered
Class Inheritance
All Implemented Interfaces
org.springframework.core.Ordered

Callback for resource cleanup at the end of a non-JPA transaction (e.g. when participating in a JtaTransactionManager transaction), fully synchronized with the ongoing transaction.
See Also
org.springframework.transaction.jta.JtaTransactionManager

Field Summary

Modifier and TypeField and Description
private final JpaDialect
private final boolean
private final Object

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
protected void
cleanupResource(EntityManagerHolder
the resource holder to process
resourceHolder
,
EntityManagerFactory
the key that the ResourceHolder was bound for
resourceKey
,
boolean
whether the transaction has committed (true) or rolled back (false)
committed
)

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.cleanupResource.

Perform a cleanup on the given resource (which is left bound to the thread).
protected void
flushResource(EntityManagerHolder
the resource holder to flush
resourceHolder
)

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.flushResource.

Flush callback for the given resource holder.
public int
protected void
releaseResource(EntityManagerHolder
the resource holder to process
resourceHolder
,
EntityManagerFactory
the key that the ResourceHolder was bound for
resourceKey
)

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.releaseResource.

Release the given resource (after it has been unbound from the thread).
protected boolean
shouldUnbindAtCompletion()

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.shouldUnbindAtCompletion.

Return whether this holder should be unbound at completion (or should rather be left bound to the thread after the transaction).
Inherited from org.springframework.transaction.support.ResourceHolderSynchronization:
afterCommitafterCompletionbeforeCommitbeforeCompletionflushprocessResourceAfterCommitresumeshouldReleaseAfterCompletionshouldReleaseBeforeCompletionsuspend

Field Detail

jpaDialectback to summary
private final JpaDialect jpaDialect
Annotations
@Nullable
newEntityManagerback to summary
private final boolean newEntityManager
transactionDataback to summary
private final Object transactionData
Annotations
@Nullable

Constructor Detail

TransactionalEntityManagerSynchronizationback to summary
public TransactionalEntityManagerSynchronization(EntityManagerHolder emHolder, EntityManagerFactory emf, Object txData, boolean newEm)

Method Detail

cleanupResourceback to summary
protected void cleanupResource(EntityManagerHolder resourceHolder, EntityManagerFactory resourceKey, boolean committed)

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.cleanupResource.

Doc from org.springframework.transaction.support.ResourceHolderSynchronization.cleanupResource.

Perform a cleanup on the given resource (which is left bound to the thread).

Parameters
resourceHolder:EntityManagerHolder

the resource holder to process

resourceKey:EntityManagerFactory

the key that the ResourceHolder was bound for

committed:boolean

whether the transaction has committed (true) or rolled back (false)

Annotations
@Override
flushResourceback to summary
protected void flushResource(EntityManagerHolder resourceHolder)

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.flushResource.

Doc from org.springframework.transaction.support.ResourceHolderSynchronization.flushResource.

Flush callback for the given resource holder.

Parameters
resourceHolder:EntityManagerHolder

the resource holder to flush

Annotations
@Override
getOrderback to summary
public int getOrder()

Overrides default org.springframework.transaction.support.TransactionSynchronization.getOrder.

Implements org.springframework.core.Ordered.getOrder.

Doc from org.springframework.core.Ordered.getOrder.

Get the order value of this object.

Higher values are interpreted as lower priority. As a consequence, the object with the lowest value has the highest priority (somewhat analogous to Servlet load-on-startup values).

Same order values will result in arbitrary sort positions for the affected objects.

Returns:int

the order value

Annotations
@Override
releaseResourceback to summary
protected void releaseResource(EntityManagerHolder resourceHolder, EntityManagerFactory resourceKey)

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.releaseResource.

Doc from org.springframework.transaction.support.ResourceHolderSynchronization.releaseResource.

Release the given resource (after it has been unbound from the thread).

Parameters
resourceHolder:EntityManagerHolder

the resource holder to process

resourceKey:EntityManagerFactory

the key that the ResourceHolder was bound for

Annotations
@Override
shouldUnbindAtCompletionback to summary
protected boolean shouldUnbindAtCompletion()

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.shouldUnbindAtCompletion.

Doc from org.springframework.transaction.support.ResourceHolderSynchronization.shouldUnbindAtCompletion.

Return whether this holder should be unbound at completion (or should rather be left bound to the thread after the transaction).

The default implementation returns true.

Annotations
@Override
org.springframework.orm.jpa back to summary

private Class EntityManagerFactoryUtils.TransactionScopedEntityManagerSynchronization

extends ResourceHolderSynchronization<EntityManagerHolder, EntityManagerFactory>
implements Ordered
Class Inheritance
All Implemented Interfaces
org.springframework.core.Ordered

Minimal callback that just closes the EntityManager at the end of the transaction.

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public int
protected void
releaseResource(EntityManagerHolder
the resource holder to process
resourceHolder
,
EntityManagerFactory
the key that the ResourceHolder was bound for
resourceKey
)

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.releaseResource.

Release the given resource (after it has been unbound from the thread).
Inherited from org.springframework.transaction.support.ResourceHolderSynchronization:
afterCommitafterCompletionbeforeCommitbeforeCompletioncleanupResourceflushflushResourceprocessResourceAfterCommitresumeshouldReleaseAfterCompletionshouldReleaseBeforeCompletionshouldUnbindAtCompletionsuspend

Constructor Detail

TransactionScopedEntityManagerSynchronizationback to summary
public TransactionScopedEntityManagerSynchronization(EntityManagerHolder emHolder, EntityManagerFactory emf)

Method Detail

getOrderback to summary
public int getOrder()

Overrides default org.springframework.transaction.support.TransactionSynchronization.getOrder.

Implements org.springframework.core.Ordered.getOrder.

Doc from org.springframework.core.Ordered.getOrder.

Get the order value of this object.

Higher values are interpreted as lower priority. As a consequence, the object with the lowest value has the highest priority (somewhat analogous to Servlet load-on-startup values).

Same order values will result in arbitrary sort positions for the affected objects.

Returns:int

the order value

Annotations
@Override
releaseResourceback to summary
protected void releaseResource(EntityManagerHolder resourceHolder, EntityManagerFactory resourceKey)

Overrides org.springframework.transaction.support.ResourceHolderSynchronization.releaseResource.

Doc from org.springframework.transaction.support.ResourceHolderSynchronization.releaseResource.

Release the given resource (after it has been unbound from the thread).

Parameters
resourceHolder:EntityManagerHolder

the resource holder to process

resourceKey:EntityManagerFactory

the key that the ResourceHolder was bound for

Annotations
@Override