spring-orm

org.springframework.orm.jpa.support
Class PersistenceAnnotationBeanPostProcessor

java.lang.Object
  extended by org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
All Implemented Interfaces:
java.io.Serializable, org.springframework.beans.factory.Aware, org.springframework.beans.factory.BeanFactoryAware, org.springframework.beans.factory.config.BeanPostProcessor, org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor, org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor, org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor, org.springframework.core.Ordered, org.springframework.core.PriorityOrdered

public class PersistenceAnnotationBeanPostProcessor
extends java.lang.Object
implements org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor, org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor, org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor, org.springframework.core.PriorityOrdered, org.springframework.beans.factory.BeanFactoryAware, java.io.Serializable

BeanPostProcessor that processes PersistenceUnit and PersistenceContext annotations, for injection of the corresponding JPA resources EntityManagerFactory and EntityManager. Any such annotated fields or methods in any Spring-managed object will automatically be injected.

This post-processor will inject sub-interfaces of EntityManagerFactory and EntityManager if the annotated fields or methods are declared as such. The actual type will be verified early, with the exception of a shared ("transactional") EntityManager reference, where type mismatches might be detected as late as on the first actual invocation.

Note: In the present implementation, PersistenceAnnotationBeanPostProcessor only supports @PersistenceUnit and @PersistenceContext with the "unitName" attribute, or no attribute at all (for the default unit). If those annotations are present with the "name" attribute at the class level, they will simply be ignored, since those only serve as deployment hint (as per the Java EE 5 specification).

This post-processor can either obtain EntityManagerFactory beans defined in the Spring application context (the default), or obtain EntityManagerFactory references from JNDI ("persistence unit references"). In the bean case, the persistence unit name will be matched against the actual deployed unit, with the bean name used as fallback unit name if no deployed name found. Typically, Spring's LocalContainerEntityManagerFactoryBean will be used for setting up such EntityManagerFactory beans. Alternatively, such beans may also be obtained from JNDI, e.g. using the jee:jndi-lookup XML configuration element (with the bean name matching the requested unit name). In both cases, the post-processor definition will look as simple as this:

 <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
In the JNDI case, specify the corresponding JNDI names in this post-processor's "persistenceUnits" map, typically with matching persistence-unit-ref entries in the Java EE deployment descriptor. By default, those names are considered as resource references (according to the Java EE resource-ref convention), located underneath the "java:comp/env/" namespace. For example:
 <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
   <property name="persistenceUnits">
     <map/gt;
       <entry key="unit1" value="persistence/unit1"/>
       <entry key="unit2" value="persistence/unit2"/>
     </map/gt;
   </property>
 </bean>
In this case, the specified persistence units will always be resolved in JNDI rather than as Spring-defined beans. The entire persistence unit deployment, including the weaving of persistent classes, is then up to the Java EE server. Persistence contexts (i.e. EntityManager references) will be built based on those server-provided EntityManagerFactory references, using Spring's own transaction synchronization facilities for transactional EntityManager handling (typically with Spring's @Transactional annotation for demarcation and JtaTransactionManager as backend).

If you prefer the Java EE server's own EntityManager handling, specify entries in this post-processor's "persistenceContexts" map (or "extendedPersistenceContexts" map, typically with matching persistence-context-ref entries in the Java EE deployment descriptor. For example:

 <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
   <property name="persistenceContexts">
     <map/gt;
       <entry key="unit1" value="persistence/context1"/>
       <entry key="unit2" value="persistence/context2"/>
     </map/gt;
   </property>
 </bean>
If the application only obtains EntityManager references in the first place, this is all you need to specify. If you need EntityManagerFactory references as well, specify entries for both "persistenceUnits" and "persistenceContexts", pointing to matching JNDI locations.

NOTE: In general, do not inject EXTENDED EntityManagers into STATELESS beans, i.e. do not use @PersistenceContext with type EXTENDED in Spring beans defined with scope 'singleton' (Spring's default scope). Extended EntityManagers are not thread-safe, hence they must not be used in concurrently accessed beans (which Spring-managed singletons usually are).

Note: A default PersistenceAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom PersistenceAnnotationBeanPostProcessor bean definition.

Since:
2.0
Author:
Rod Johnson, Juergen Hoeller
See Also:
PersistenceUnit, PersistenceContext, Serialized Form

Field Summary
 
Fields inherited from interface org.springframework.core.Ordered
HIGHEST_PRECEDENCE, LOWEST_PRECEDENCE
 
Constructor Summary
PersistenceAnnotationBeanPostProcessor()
           
 
Method Summary
protected  javax.persistence.EntityManagerFactory findDefaultEntityManagerFactory(java.lang.String requestingBeanName)
          Find a single default EntityManagerFactory in the Spring application context.
protected  javax.persistence.EntityManagerFactory findEntityManagerFactory(java.lang.String unitName, java.lang.String requestingBeanName)
          Find an EntityManagerFactory with the given name in the current Spring application context, falling back to a single default EntityManagerFactory (if any) in case of no unit name specified.
protected  javax.persistence.EntityManagerFactory findNamedEntityManagerFactory(java.lang.String unitName, java.lang.String requestingBeanName)
          Find an EntityManagerFactory with the given name in the current Spring application context.
 int getOrder()
           
protected  javax.persistence.EntityManager getPersistenceContext(java.lang.String unitName, boolean extended)
          Return a specified persistence context for the given unit name, as defined through the "persistenceContexts" (or "extendedPersistenceContexts") map.
protected  javax.persistence.EntityManagerFactory getPersistenceUnit(java.lang.String unitName)
          Return a specified persistence unit for the given unit name, as defined through the "persistenceUnits" map.
protected
<T> T
lookup(java.lang.String jndiName, java.lang.Class<T> requiredType)
          Perform a JNDI lookup for the given resource by name.
 java.lang.Object postProcessAfterInitialization(java.lang.Object bean, java.lang.String beanName)
           
 boolean postProcessAfterInstantiation(java.lang.Object bean, java.lang.String beanName)
           
 void postProcessBeforeDestruction(java.lang.Object bean, java.lang.String beanName)
           
 java.lang.Object postProcessBeforeInitialization(java.lang.Object bean, java.lang.String beanName)
           
 java.lang.Object postProcessBeforeInstantiation(java.lang.Class<?> beanClass, java.lang.String beanName)
           
 void postProcessMergedBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition beanDefinition, java.lang.Class<?> beanType, java.lang.String beanName)
           
 org.springframework.beans.PropertyValues postProcessPropertyValues(org.springframework.beans.PropertyValues pvs, java.beans.PropertyDescriptor[] pds, java.lang.Object bean, java.lang.String beanName)
           
 void setBeanFactory(org.springframework.beans.factory.BeanFactory beanFactory)
           
 void setDefaultPersistenceUnitName(java.lang.String unitName)
          Specify the default persistence unit name, to be used in case of no unit name specified in an @PersistenceUnit / @PersistenceContext annotation.
 void setExtendedPersistenceContexts(java.util.Map<java.lang.String,java.lang.String> extendedPersistenceContexts)
          Specify the extended persistence contexts for EntityManager lookups, as a Map from persistence unit name to persistence context JNDI name (which needs to resolve to an EntityManager instance).
 void setJndiEnvironment(java.util.Properties jndiEnvironment)
          Set the JNDI environment to use for JNDI lookups.
 void setJndiTemplate(java.lang.Object jndiTemplate)
          Set the JNDI template to use for JNDI lookups.
 void setOrder(int order)
           
 void setPersistenceContexts(java.util.Map<java.lang.String,java.lang.String> persistenceContexts)
          Specify the transactional persistence contexts for EntityManager lookups, as a Map from persistence unit name to persistence context JNDI name (which needs to resolve to an EntityManager instance).
 void setPersistenceUnits(java.util.Map<java.lang.String,java.lang.String> persistenceUnits)
          Specify the persistence units for EntityManagerFactory lookups, as a Map from persistence unit name to persistence unit JNDI name (which needs to resolve to an EntityManagerFactory instance).
 void setResourceRef(boolean resourceRef)
          Set whether the lookup occurs in a J2EE container, i.e.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

PersistenceAnnotationBeanPostProcessor

public PersistenceAnnotationBeanPostProcessor()
Method Detail

setJndiTemplate

public void setJndiTemplate(java.lang.Object jndiTemplate)
Set the JNDI template to use for JNDI lookups.

See Also:
JndiAccessor.setJndiTemplate(org.springframework.jndi.JndiTemplate)

setJndiEnvironment

public void setJndiEnvironment(java.util.Properties jndiEnvironment)
Set the JNDI environment to use for JNDI lookups.

See Also:
JndiAccessor.setJndiEnvironment(java.util.Properties)

setResourceRef

public void setResourceRef(boolean resourceRef)
Set whether the lookup occurs in a J2EE container, i.e. if the prefix "java:comp/env/" needs to be added if the JNDI name doesn't already contain it. PersistenceAnnotationBeanPostProcessor's default is "true".

See Also:
JndiLocatorSupport.setResourceRef(boolean)

setPersistenceUnits

public void setPersistenceUnits(java.util.Map<java.lang.String,java.lang.String> persistenceUnits)
Specify the persistence units for EntityManagerFactory lookups, as a Map from persistence unit name to persistence unit JNDI name (which needs to resolve to an EntityManagerFactory instance).

JNDI names specified here should refer to persistence-unit-ref entries in the Java EE deployment descriptor, matching the target persistence unit.

In case of no unit name specified in the annotation, the specified value for the default persistence unit will be taken (by default, the value mapped to the empty String), or simply the single persistence unit if there is only one.

This is mainly intended for use in a Java EE 5 environment, with all lookup driven by the standard JPA annotations, and all EntityManagerFactory references obtained from JNDI. No separate EntityManagerFactory bean definitions are necessary in such a scenario.

If no corresponding "persistenceContexts"/"extendedPersistenceContexts" are specified, @PersistenceContext will be resolved to EntityManagers built on top of the EntityManagerFactory defined here. Note that those will be Spring-managed EntityManagers, which implement transaction synchronization based on Spring's facilities. If you prefer the Java EE 5 server's own EntityManager handling, specify corresponding "persistenceContexts"/"extendedPersistenceContexts".


setPersistenceContexts

public void setPersistenceContexts(java.util.Map<java.lang.String,java.lang.String> persistenceContexts)
Specify the transactional persistence contexts for EntityManager lookups, as a Map from persistence unit name to persistence context JNDI name (which needs to resolve to an EntityManager instance).

JNDI names specified here should refer to persistence-context-ref entries in the Java EE deployment descriptors, matching the target persistence unit and being set up with persistence context type Transaction.

In case of no unit name specified in the annotation, the specified value for the default persistence unit will be taken (by default, the value mapped to the empty String), or simply the single persistence unit if there is only one.

This is mainly intended for use in a Java EE 5 environment, with all lookup driven by the standard JPA annotations, and all EntityManager references obtained from JNDI. No separate EntityManagerFactory bean definitions are necessary in such a scenario, and all EntityManager handling is done by the Java EE 5 server itself.


setExtendedPersistenceContexts

public void setExtendedPersistenceContexts(java.util.Map<java.lang.String,java.lang.String> extendedPersistenceContexts)
Specify the extended persistence contexts for EntityManager lookups, as a Map from persistence unit name to persistence context JNDI name (which needs to resolve to an EntityManager instance).

JNDI names specified here should refer to persistence-context-ref entries in the Java EE deployment descriptors, matching the target persistence unit and being set up with persistence context type Extended.

In case of no unit name specified in the annotation, the specified value for the default persistence unit will be taken (by default, the value mapped to the empty String), or simply the single persistence unit if there is only one.

This is mainly intended for use in a Java EE 5 environment, with all lookup driven by the standard JPA annotations, and all EntityManager references obtained from JNDI. No separate EntityManagerFactory bean definitions are necessary in such a scenario, and all EntityManager handling is done by the Java EE 5 server itself.


setDefaultPersistenceUnitName

public void setDefaultPersistenceUnitName(java.lang.String unitName)
Specify the default persistence unit name, to be used in case of no unit name specified in an @PersistenceUnit / @PersistenceContext annotation.

This is mainly intended for lookups in the application context, indicating the target persistence unit name (typically matching the bean name), but also applies to lookups in the "persistenceUnits" / "persistenceContexts" / "extendedPersistenceContexts" map, avoiding the need for duplicated mappings for the empty String there.

Default is to check for a single EntityManagerFactory bean in the Spring application context, if any. If there are multiple such factories, either specify this default persistence unit name or explicitly refer to named persistence units in your annotations.


setOrder

public void setOrder(int order)

getOrder

public int getOrder()
Specified by:
getOrder in interface org.springframework.core.Ordered

setBeanFactory

public void setBeanFactory(org.springframework.beans.factory.BeanFactory beanFactory)
Specified by:
setBeanFactory in interface org.springframework.beans.factory.BeanFactoryAware

postProcessMergedBeanDefinition

public void postProcessMergedBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition beanDefinition,
                                            java.lang.Class<?> beanType,
                                            java.lang.String beanName)
Specified by:
postProcessMergedBeanDefinition in interface org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor

postProcessBeforeInstantiation

public java.lang.Object postProcessBeforeInstantiation(java.lang.Class<?> beanClass,
                                                       java.lang.String beanName)
                                                throws org.springframework.beans.BeansException
Specified by:
postProcessBeforeInstantiation in interface org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
Throws:
org.springframework.beans.BeansException

postProcessAfterInstantiation

public boolean postProcessAfterInstantiation(java.lang.Object bean,
                                             java.lang.String beanName)
                                      throws org.springframework.beans.BeansException
Specified by:
postProcessAfterInstantiation in interface org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
Throws:
org.springframework.beans.BeansException

postProcessPropertyValues

public org.springframework.beans.PropertyValues postProcessPropertyValues(org.springframework.beans.PropertyValues pvs,
                                                                          java.beans.PropertyDescriptor[] pds,
                                                                          java.lang.Object bean,
                                                                          java.lang.String beanName)
                                                                   throws org.springframework.beans.BeansException
Specified by:
postProcessPropertyValues in interface org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
Throws:
org.springframework.beans.BeansException

postProcessBeforeInitialization

public java.lang.Object postProcessBeforeInitialization(java.lang.Object bean,
                                                        java.lang.String beanName)
                                                 throws org.springframework.beans.BeansException
Specified by:
postProcessBeforeInitialization in interface org.springframework.beans.factory.config.BeanPostProcessor
Throws:
org.springframework.beans.BeansException

postProcessAfterInitialization

public java.lang.Object postProcessAfterInitialization(java.lang.Object bean,
                                                       java.lang.String beanName)
                                                throws org.springframework.beans.BeansException
Specified by:
postProcessAfterInitialization in interface org.springframework.beans.factory.config.BeanPostProcessor
Throws:
org.springframework.beans.BeansException

postProcessBeforeDestruction

public void postProcessBeforeDestruction(java.lang.Object bean,
                                         java.lang.String beanName)
                                  throws org.springframework.beans.BeansException
Specified by:
postProcessBeforeDestruction in interface org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
Throws:
org.springframework.beans.BeansException

getPersistenceUnit

protected javax.persistence.EntityManagerFactory getPersistenceUnit(java.lang.String unitName)
Return a specified persistence unit for the given unit name, as defined through the "persistenceUnits" map.

Parameters:
unitName - the name of the persistence unit
Returns:
the corresponding EntityManagerFactory, or null if none found
See Also:
setPersistenceUnits(java.util.Map)

getPersistenceContext

protected javax.persistence.EntityManager getPersistenceContext(java.lang.String unitName,
                                                                boolean extended)
Return a specified persistence context for the given unit name, as defined through the "persistenceContexts" (or "extendedPersistenceContexts") map.

Parameters:
unitName - the name of the persistence unit
extended - whether to obtain an extended persistence context
Returns:
the corresponding EntityManager, or null if none found
See Also:
setPersistenceContexts(java.util.Map), setExtendedPersistenceContexts(java.util.Map)

findEntityManagerFactory

protected javax.persistence.EntityManagerFactory findEntityManagerFactory(java.lang.String unitName,
                                                                          java.lang.String requestingBeanName)
                                                                   throws org.springframework.beans.factory.NoSuchBeanDefinitionException
Find an EntityManagerFactory with the given name in the current Spring application context, falling back to a single default EntityManagerFactory (if any) in case of no unit name specified.

Parameters:
unitName - the name of the persistence unit (may be null or empty)
requestingBeanName - the name of the requesting bean
Returns:
the EntityManagerFactory
Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException - if there is no such EntityManagerFactory in the context

findNamedEntityManagerFactory

protected javax.persistence.EntityManagerFactory findNamedEntityManagerFactory(java.lang.String unitName,
                                                                               java.lang.String requestingBeanName)
                                                                        throws org.springframework.beans.factory.NoSuchBeanDefinitionException
Find an EntityManagerFactory with the given name in the current Spring application context.

Parameters:
unitName - the name of the persistence unit (never empty)
requestingBeanName - the name of the requesting bean
Returns:
the EntityManagerFactory
Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException - if there is no such EntityManagerFactory in the context

findDefaultEntityManagerFactory

protected javax.persistence.EntityManagerFactory findDefaultEntityManagerFactory(java.lang.String requestingBeanName)
                                                                          throws org.springframework.beans.factory.NoSuchBeanDefinitionException
Find a single default EntityManagerFactory in the Spring application context.

Returns:
the default EntityManagerFactory
Throws:
org.springframework.beans.factory.NoSuchBeanDefinitionException - if there is no single EntityManagerFactory in the context

lookup

protected <T> T lookup(java.lang.String jndiName,
                       java.lang.Class<T> requiredType)
            throws java.lang.Exception
Perform a JNDI lookup for the given resource by name.

Called for EntityManagerFactory and EntityManager lookup when JNDI names are mapped for specific persistence units.

Parameters:
jndiName - the JNDI name to look up
requiredType - the required type of the object
Returns:
the obtained object
Throws:
java.lang.Exception - if the JNDI lookup failed

spring-orm