Class AbstractEntityManagerFactoryBean

java.lang.Object
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean
All Implemented Interfaces:
Serializable, Aware, BeanClassLoaderAware, BeanFactoryAware, BeanNameAware, DisposableBean, FactoryBean<jakarta.persistence.EntityManagerFactory>, InitializingBean, SmartFactoryBean<jakarta.persistence.EntityManagerFactory>, SmartInitializingSingleton, PersistenceExceptionTranslator, EntityManagerFactoryInfo
Direct Known Subclasses:
LocalContainerEntityManagerFactoryBean, LocalEntityManagerFactoryBean

public abstract class AbstractEntityManagerFactoryBean extends Object implements SmartFactoryBean<jakarta.persistence.EntityManagerFactory>, BeanClassLoaderAware, BeanFactoryAware, BeanNameAware, InitializingBean, SmartInitializingSingleton, DisposableBean, EntityManagerFactoryInfo, PersistenceExceptionTranslator, Serializable
Abstract FactoryBean that creates a local JPA EntityManagerFactory instance within a Spring application context. As of 7.0, it additionally exposes a shared EntityManager instance through SmartFactoryBean, making EntityManager available for dependency injection as well.

Encapsulates the common functionality between the different JPA bootstrap contracts (standalone as well as container).

Implements support for standard JPA configuration conventions as well as Spring's customizable JpaVendorAdapter mechanism, and controls the EntityManagerFactory's lifecycle.

This class also implements the PersistenceExceptionTranslator interface, as autodetected by Spring's PersistenceExceptionTranslationPostProcessor, for AOP-based translation of native exceptions to Spring DataAccessExceptions. Hence, the presence of, for example, LocalEntityManagerFactoryBean automatically enables a PersistenceExceptionTranslationPostProcessor to translate JPA exceptions.

Since:
2.0
Author:
Juergen Hoeller, Rod Johnson
See Also:
  • Field Details

    • logger

      protected final org.apache.commons.logging.Log logger
      Logger available to subclasses.
  • Constructor Details

    • AbstractEntityManagerFactoryBean

      public AbstractEntityManagerFactoryBean()
  • Method Details

    • setPersistenceProviderClass

      public void setPersistenceProviderClass(Class<? extends jakarta.persistence.spi.PersistenceProvider> persistenceProviderClass)
      Set the PersistenceProvider implementation class to use for creating the EntityManagerFactory. If not specified, the persistence provider will be taken from the JpaVendorAdapter (if any) or retrieved through scanning (as far as possible).
      See Also:
    • setPersistenceProvider

      public void setPersistenceProvider(@Nullable jakarta.persistence.spi.PersistenceProvider persistenceProvider)
      Set the PersistenceProvider instance to use for creating the EntityManagerFactory. If not specified, the persistence provider will be taken from the JpaVendorAdapter (if any) or determined by the persistence unit deployment descriptor (as far as possible).
      See Also:
    • getPersistenceProvider

      public @Nullable jakarta.persistence.spi.PersistenceProvider getPersistenceProvider()
      Description copied from interface: EntityManagerFactoryInfo
      Return the underlying PersistenceProvider that the underlying EntityManagerFactory was created with.
      Specified by:
      getPersistenceProvider in interface EntityManagerFactoryInfo
      Returns:
      the PersistenceProvider used to create this EntityManagerFactory, or null if the standard JPA provider autodetection process was used to configure the EntityManagerFactory
    • setPersistenceUnitName

      public void setPersistenceUnitName(@Nullable String persistenceUnitName)
      Specify the name of the EntityManagerFactory configuration.

      Default is none, indicating the default EntityManagerFactory configuration. The persistence provider will throw an exception if ambiguous EntityManager configurations are found.

      See Also:
      • Persistence.createEntityManagerFactory(String)
    • getPersistenceUnitName

      public @Nullable String getPersistenceUnitName()
      Description copied from interface: EntityManagerFactoryInfo
      Return the name of the persistence unit used to create this EntityManagerFactory, or null if it is an unnamed default.

      If getPersistenceUnitInfo() returns non-null, the result of getPersistenceUnitName() must be equal to the value returned by PersistenceUnitInfo.getPersistenceUnitName().

      Specified by:
      getPersistenceUnitName in interface EntityManagerFactoryInfo
      See Also:
    • setJpaProperties

      public void setJpaProperties(Properties jpaProperties)
      Specify JPA properties, to be passed into Persistence.createEntityManagerFactory (if any).

      Can be populated with a String "value" (parsed via PropertiesEditor) or a "props" element in XML bean definitions.

      See Also:
      • Persistence.createEntityManagerFactory(String, Map)
      • PersistenceProvider.createContainerEntityManagerFactory(PersistenceUnitInfo, Map)
    • setJpaPropertyMap

      public void setJpaPropertyMap(@Nullable Map<String,?> jpaProperties)
      Specify JPA properties as a Map, to be passed into Persistence.createEntityManagerFactory (if any).

      Can be populated with a "map" or "props" element in XML bean definitions.

      See Also:
      • Persistence.createEntityManagerFactory(String, Map)
      • PersistenceProvider.createContainerEntityManagerFactory(PersistenceUnitInfo, Map)
    • getJpaPropertyMap

      public Map<String,Object> getJpaPropertyMap()
      Allow Map access to the JPA properties to be passed to the persistence provider, with the option to add or override specific entries.

      Useful for specifying entries directly, for example via jpaPropertyMap[myKey].

    • setEntityManagerFactoryInterface

      public void setEntityManagerFactoryInterface(Class<? extends jakarta.persistence.EntityManagerFactory> emfInterface)
      Specify the (potentially vendor-specific) EntityManagerFactory interface that this EntityManagerFactory proxy is supposed to implement.

      The default will be taken from the specific JpaVendorAdapter, if any, or set to the standard jakarta.persistence.EntityManagerFactory interface else.

      See Also:
    • setEntityManagerInterface

      public void setEntityManagerInterface(@Nullable Class<? extends jakarta.persistence.EntityManager> emInterface)
      Specify the (potentially vendor-specific) EntityManager interface that this factory's EntityManagers are supposed to implement.

      The default will be taken from the specific JpaVendorAdapter, if any, or set to the standard jakarta.persistence.EntityManager interface else.

      See Also:
    • getEntityManagerInterface

      public @Nullable Class<? extends jakarta.persistence.EntityManager> getEntityManagerInterface()
      Description copied from interface: EntityManagerFactoryInfo
      Return the (potentially vendor-specific) EntityManager interface that this factory's EntityManagers will implement.

      A null return value suggests that autodetection is supposed to happen: either based on a target EntityManager instance or simply defaulting to jakarta.persistence.EntityManager.

      Specified by:
      getEntityManagerInterface in interface EntityManagerFactoryInfo
    • setJpaDialect

      public void setJpaDialect(@Nullable JpaDialect jpaDialect)
      Specify the vendor-specific JpaDialect implementation to associate with this EntityManagerFactory. This will be exposed through the EntityManagerFactoryInfo interface, to be picked up as default dialect by accessors that intend to use JpaDialect functionality.
      See Also:
    • getJpaDialect

      public @Nullable JpaDialect getJpaDialect()
      Description copied from interface: EntityManagerFactoryInfo
      Return the vendor-specific JpaDialect implementation for this EntityManagerFactory, or null if not known.
      Specified by:
      getJpaDialect in interface EntityManagerFactoryInfo
    • setJpaVendorAdapter

      public void setJpaVendorAdapter(@Nullable JpaVendorAdapter jpaVendorAdapter)
      Specify the JpaVendorAdapter implementation for the desired JPA provider, if any. This will initialize appropriate defaults for the given provider, such as persistence provider class and JpaDialect, unless locally overridden in this FactoryBean.
    • getJpaVendorAdapter

      public @Nullable JpaVendorAdapter getJpaVendorAdapter()
      Return the JpaVendorAdapter implementation for this EntityManagerFactory, or null if not known.
    • setEntityManagerInitializer

      public void setEntityManagerInitializer(Consumer<jakarta.persistence.EntityManager> entityManagerInitializer)
      Specify a callback for customizing every EntityManager created by the exposed EntityManagerFactory.

      This is an alternative to a JpaVendorAdapter-level postProcessEntityManager implementation, enabling convenient customizations for application purposes, for example, setting Hibernate filters.

      Since:
      5.3
      See Also:
    • setBootstrapExecutor

      public void setBootstrapExecutor(@Nullable AsyncTaskExecutor bootstrapExecutor)
      Specify an asynchronous executor for background bootstrapping, for example, a SimpleAsyncTaskExecutor.

      EntityManagerFactory initialization will then switch into background bootstrap mode, with a EntityManagerFactory proxy immediately returned for injection purposes instead of waiting for the JPA provider's bootstrapping to complete. However, note that the first actual call to a EntityManagerFactory method will then block until the JPA provider's bootstrapping completed, if not ready by then. For maximum benefit, make sure to avoid early EntityManagerFactory calls in init methods of related beans, even for metadata introspection purposes.

      As of 6.2, JPA initialization is enforced before context refresh completion, waiting for asynchronous bootstrapping to complete by then.

      Since:
      4.3
    • getBootstrapExecutor

      public @Nullable AsyncTaskExecutor getBootstrapExecutor()
      Return the asynchronous executor for background bootstrapping, if any.
      Since:
      4.3
    • setBeanClassLoader

      public void setBeanClassLoader(ClassLoader classLoader)
      Description copied from interface: BeanClassLoaderAware
      Callback that supplies the bean class loader to a bean instance.

      Invoked after the population of normal bean properties but before an initialization callback such as InitializingBean's InitializingBean.afterPropertiesSet() method or a custom init-method.

      Specified by:
      setBeanClassLoader in interface BeanClassLoaderAware
      Parameters:
      classLoader - the owning class loader
    • getBeanClassLoader

      public ClassLoader getBeanClassLoader()
      Description copied from interface: EntityManagerFactoryInfo
      Return the ClassLoader that the application's beans are loaded with.

      Proxies will be generated in this ClassLoader.

      Specified by:
      getBeanClassLoader in interface EntityManagerFactoryInfo
    • setBeanFactory

      public void setBeanFactory(BeanFactory beanFactory)
      Description copied from interface: BeanFactoryAware
      Callback that supplies the owning factory to a bean instance.

      Invoked after the population of normal bean properties but before an initialization callback such as InitializingBean.afterPropertiesSet() or a custom init-method.

      Specified by:
      setBeanFactory in interface BeanFactoryAware
      Parameters:
      beanFactory - owning BeanFactory (never null). The bean can immediately call methods on the factory.
      See Also:
    • getBeanFactory

      protected @Nullable BeanFactory getBeanFactory()
    • setBeanName

      public void setBeanName(String name)
      Description copied from interface: BeanNameAware
      Set the name of the bean in the bean factory that created this bean.

      Invoked after population of normal bean properties but before an init callback such as InitializingBean.afterPropertiesSet() or a custom init-method.

      Specified by:
      setBeanName in interface BeanNameAware
      Parameters:
      name - the name of the bean in the factory. Note that this name is the actual bean name used in the factory, which may differ from the originally specified name: in particular for inner bean names, the actual bean name might have been made unique through appending "#..." suffixes. Use the BeanFactoryUtils.originalBeanName(String) method to extract the original bean name (without suffix), if desired.
    • getBeanName

      protected @Nullable String getBeanName()
    • afterPropertiesSet

      public void afterPropertiesSet() throws jakarta.persistence.PersistenceException
      Description copied from interface: InitializingBean
      Invoked by the containing BeanFactory after it has set all bean properties and satisfied BeanFactoryAware, ApplicationContextAware etc.

      This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.

      Specified by:
      afterPropertiesSet in interface InitializingBean
      Throws:
      jakarta.persistence.PersistenceException
    • afterSingletonsInstantiated

      public void afterSingletonsInstantiated()
      Description copied from interface: SmartInitializingSingleton
      Invoked right at the end of the singleton pre-instantiation phase, with a guarantee that all regular singleton beans have been created already. ListableBeanFactory.getBeansOfType(Class) calls within this method won't trigger accidental side effects during bootstrap.

      NOTE: This callback won't be triggered for singleton beans lazily initialized on demand after BeanFactory bootstrap, and not for any other bean scope either. Carefully use it for beans with the intended bootstrap semantics only.

      Specified by:
      afterSingletonsInstantiated in interface SmartInitializingSingleton
    • createEntityManagerFactoryProxy

      protected jakarta.persistence.EntityManagerFactory createEntityManagerFactoryProxy(@Nullable jakarta.persistence.EntityManagerFactory emf)
      Create a proxy for the given EntityManagerFactory. We do this to be able to return a transaction-aware proxy for an application-managed EntityManager.
      Parameters:
      emf - the EntityManagerFactory as returned by the persistence provider, if initialized already
      Returns:
      the EntityManagerFactory proxy
    • createNativeEntityManagerFactory

      protected abstract jakarta.persistence.EntityManagerFactory createNativeEntityManagerFactory() throws jakarta.persistence.PersistenceException
      Subclasses must implement this method to create the EntityManagerFactory that will be returned by the getObject() method.
      Returns:
      the EntityManagerFactory instance returned by this FactoryBean
      Throws:
      jakarta.persistence.PersistenceException - if the EntityManager cannot be created
    • translateExceptionIfPossible

      public @Nullable DataAccessException translateExceptionIfPossible(RuntimeException ex)
      Implementation of the PersistenceExceptionTranslator interface, as autodetected by Spring's PersistenceExceptionTranslationPostProcessor.

      Uses the dialect's conversion if possible; otherwise falls back to standard JPA exception conversion.

      Specified by:
      translateExceptionIfPossible in interface PersistenceExceptionTranslator
      Parameters:
      ex - a RuntimeException to translate
      Returns:
      the corresponding DataAccessException (or null if the exception could not be translated, as in this case it may result from user code rather than from an actual persistence problem)
      See Also:
    • getNativeEntityManagerFactory

      public jakarta.persistence.EntityManagerFactory getNativeEntityManagerFactory()
      Description copied from interface: EntityManagerFactoryInfo
      Return the raw underlying EntityManagerFactory.
      Specified by:
      getNativeEntityManagerFactory in interface EntityManagerFactoryInfo
      Returns:
      the unadorned EntityManagerFactory (never null)
    • createNativeEntityManager

      public jakarta.persistence.EntityManager createNativeEntityManager(@Nullable Map<?,?> properties)
      Description copied from interface: EntityManagerFactoryInfo
      Create a native JPA EntityManager to be used as the framework-managed resource behind an application-level EntityManager handle.

      This exposes a native EntityManager from the underlying native EntityManagerFactory, taking JpaVendorAdapter.postProcessEntityManager(EntityManager) into account.

      Specified by:
      createNativeEntityManager in interface EntityManagerFactoryInfo
      See Also:
    • postProcessEntityManager

      protected void postProcessEntityManager(jakarta.persistence.EntityManager rawEntityManager)
      Optional callback for post-processing the native EntityManager before active use.

      The default implementation delegates to JpaVendorAdapter.postProcessEntityManager(EntityManager), if available.

      Parameters:
      rawEntityManager - the EntityManager to post-process
      Since:
      5.3
      See Also:
    • getPersistenceUnitInfo

      public @Nullable jakarta.persistence.spi.PersistenceUnitInfo getPersistenceUnitInfo()
      Description copied from interface: EntityManagerFactoryInfo
      Return the PersistenceUnitInfo used to create this EntityManagerFactory, if the in-container API was used.
      Specified by:
      getPersistenceUnitInfo in interface EntityManagerFactoryInfo
      Returns:
      the PersistenceUnitInfo used to create this EntityManagerFactory, or null if the in-container contract was not used to configure the EntityManagerFactory
    • getDataSource

      public @Nullable DataSource getDataSource()
      Description copied from interface: EntityManagerFactoryInfo
      Return the JDBC DataSource that this EntityManagerFactory obtains its JDBC Connections from.
      Specified by:
      getDataSource in interface EntityManagerFactoryInfo
      Returns:
      the JDBC DataSource, or null if not known
    • getObject

      public @Nullable jakarta.persistence.EntityManagerFactory getObject()
      Return the singleton EntityManagerFactory.
      Specified by:
      getObject in interface FactoryBean<jakarta.persistence.EntityManagerFactory>
      Returns:
      an instance of the bean (can be null)
      See Also:
    • getObjectType

      public Class<? extends jakarta.persistence.EntityManagerFactory> getObjectType()
      Description copied from interface: FactoryBean
      Return the type of object that this FactoryBean creates, or null if not known in advance.

      This allows one to check for specific types of beans without instantiating objects, for example on autowiring.

      In the case of implementations that create a singleton object, this method should try to avoid singleton creation as far as possible; it should rather estimate the type in advance. For prototypes, returning a meaningful type here is advisable too.

      This method can be called before this FactoryBean has been fully initialized. It must not rely on state created during initialization; of course, it can still use such state if available.

      NOTE: Autowiring will simply ignore FactoryBeans that return null here. Therefore, it is highly recommended to implement this method properly, using the current state of the FactoryBean.

      Specified by:
      getObjectType in interface FactoryBean<jakarta.persistence.EntityManagerFactory>
      Returns:
      the type of object that this FactoryBean creates, or null if not known at the time of the call
      See Also:
    • getObject

      public <S> @Nullable S getObject(Class<S> type) throws Exception
      Return either the singleton EntityManagerFactory or the shared EntityManager proxy.
      Specified by:
      getObject in interface SmartFactoryBean<jakarta.persistence.EntityManagerFactory>
      Parameters:
      type - the requested type
      Returns:
      a corresponding instance managed by this factory, or null if none available
      Throws:
      Exception - in case of creation errors
      See Also:
    • supportsType

      public boolean supportsType(Class<?> type)
      Description copied from interface: SmartFactoryBean
      Determine whether this factory supports the requested type.

      By default, this supports the primary type exposed by the factory, as indicated by FactoryBean.getObjectType(). Specific factories may support additional types for dependency injection.

      Specified by:
      supportsType in interface SmartFactoryBean<jakarta.persistence.EntityManagerFactory>
      Parameters:
      type - the requested type
      Returns:
      true if SmartFactoryBean.getObject(Class) is able to return a corresponding instance, false otherwise
      See Also:
    • destroy

      public void destroy()
      Close the EntityManagerFactory on bean factory shutdown.
      Specified by:
      destroy in interface DisposableBean
    • writeReplace

      protected Object writeReplace() throws ObjectStreamException
      Throws:
      ObjectStreamException