congrats Icon
New! Announcing Tabnine Chat Beta
Learn More
Tabnine Logo
PersistenceAnnotationBeanPostProcessor
Code IndexAdd Tabnine to your IDE (free)

How to use
PersistenceAnnotationBeanPostProcessor
in
org.springframework.orm.jpa.support

Best Java code snippets using org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor (Showing top 20 results out of 315)

origin: AxonFramework/AxonFramework

@Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
  return new PersistenceAnnotationBeanPostProcessor();
}
origin: spring-projects/spring-framework

private InjectionMetadata findPersistenceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs) {
  // Fall back to class name as cache key, for backwards compatibility with custom callers.
  String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
  // Quick check on the concurrent map first, with minimal locking.
  InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
  if (InjectionMetadata.needsRefresh(metadata, clazz)) {
    synchronized (this.injectionMetadataCache) {
      metadata = this.injectionMetadataCache.get(cacheKey);
      if (InjectionMetadata.needsRefresh(metadata, clazz)) {
        if (metadata != null) {
          metadata.clear(pvs);
        }
        metadata = buildPersistenceMetadata(clazz);
        this.injectionMetadataCache.put(cacheKey, metadata);
      }
    }
  }
  return metadata;
}
origin: spring-projects/spring-framework

/**
 * 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.
 * @param unitName the name of the persistence unit (may be {@code null} or empty)
 * @param requestingBeanName the name of the requesting bean
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 */
protected EntityManagerFactory findEntityManagerFactory(@Nullable String unitName, @Nullable String requestingBeanName)
    throws NoSuchBeanDefinitionException {
  String unitNameForLookup = (unitName != null ? unitName : "");
  if (unitNameForLookup.isEmpty()) {
    unitNameForLookup = this.defaultPersistenceUnitName;
  }
  if (!unitNameForLookup.isEmpty()) {
    return findNamedEntityManagerFactory(unitNameForLookup, requestingBeanName);
  }
  else {
    return findDefaultEntityManagerFactory(requestingBeanName);
  }
}
origin: spring-projects/spring-framework

private EntityManagerFactory resolveEntityManagerFactory(@Nullable String requestingBeanName) {
  // Obtain EntityManagerFactory from JNDI?
  EntityManagerFactory emf = getPersistenceUnit(this.unitName);
  if (emf == null) {
    // Need to search for EntityManagerFactory beans.
    emf = findEntityManagerFactory(this.unitName, requestingBeanName);
  }
  return emf;
}
origin: spring-projects/spring-framework

  private EntityManager resolveExtendedEntityManager(Object target, @Nullable String requestingBeanName) {
    // Obtain EntityManager reference from JNDI?
    EntityManager em = getPersistenceContext(this.unitName, true);
    if (em == null) {
      // No pre-built EntityManager found -> build one based on factory.
      // Obtain EntityManagerFactory from JNDI?
      EntityManagerFactory emf = getPersistenceUnit(this.unitName);
      if (emf == null) {
        // Need to search for EntityManagerFactory beans.
        emf = findEntityManagerFactory(this.unitName, requestingBeanName);
      }
      // Inject a container-managed extended EntityManager.
      em = ExtendedEntityManagerCreator.createContainerManagedEntityManager(
          emf, this.properties, this.synchronizedWithTransaction);
    }
    if (em instanceof EntityManagerProxy && beanFactory != null && requestingBeanName != null &&
        beanFactory.containsBean(requestingBeanName) && !beanFactory.isPrototype(requestingBeanName)) {
      extendedEntityManagersToClose.put(target, ((EntityManagerProxy) em).getTargetEntityManager());
    }
    return em;
  }
}
origin: spring-projects/spring-framework

@Test
public void testSinglePersistenceContextFromJndi() {
  EntityManager mockEm = mock(EntityManager.class);
  EntityManager mockEm2 = mock(EntityManager.class);
  Map<String, String> persistenceContexts = new HashMap<>();
  persistenceContexts.put("System", "pc1");
  Map<String, String> extendedPersistenceContexts = new HashMap<>();
  extendedPersistenceContexts .put("System", "pc2");
  ExpectedLookupTemplate jt = new ExpectedLookupTemplate();
  jt.addObject("java:comp/env/pc1", mockEm);
  jt.addObject("java:comp/env/pc2", mockEm2);
  DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
  PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
  bpp.setPersistenceContexts(persistenceContexts);
  bpp.setExtendedPersistenceContexts(extendedPersistenceContexts);
  bpp.setJndiTemplate(jt);
  bf.addBeanPostProcessor(bpp);
  bf.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(),
      new RootBeanDefinition(DefaultPrivatePersistenceContextField.class));
  bf.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
      new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
  DefaultPrivatePersistenceContextField bean1 = (DefaultPrivatePersistenceContextField)
      bf.getBean(DefaultPrivatePersistenceContextField.class.getName());
  DefaultPublicPersistenceContextSetter bean2 = (DefaultPublicPersistenceContextSetter)
      bf.getBean(DefaultPublicPersistenceContextSetter.class.getName());
  assertSame(mockEm, bean1.em);
  assertSame(mockEm2, bean2.em);
}
origin: spring-projects/spring-framework

@Test
public void testFieldOfWrongTypeAnnotatedWithPersistenceUnit() {
  PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor();
  try {
    pabpp.postProcessProperties(null, new FieldOfWrongTypeAnnotatedWithPersistenceUnit(), "bean");
    fail("Can't inject this field");
  }
  catch (IllegalStateException ex) {
    // Ok
  }
}
origin: spring-projects/spring-framework

@Deprecated
@Override
public PropertyValues postProcessPropertyValues(
    PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
  return postProcessProperties(pvs, bean, beanName);
}
origin: spring-projects/spring-framework

@Test
public void testPersistenceUnitsFromJndiWithDefaultUnit() {
  EntityManagerFactoryWithInfo mockEmf2 = mock(EntityManagerFactoryWithInfo.class);
  Map<String, String> persistenceUnits = new HashMap<>();
  persistenceUnits.put("System", "pu1");
  persistenceUnits.put("Person", "pu2");
  ExpectedLookupTemplate jt = new ExpectedLookupTemplate();
  jt.addObject("java:comp/env/pu1", mockEmf);
  jt.addObject("java:comp/env/pu2", mockEmf2);
  DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
  PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
  bpp.setPersistenceUnits(persistenceUnits);
  bpp.setDefaultPersistenceUnitName("System");
  bpp.setJndiTemplate(jt);
  bf.addBeanPostProcessor(bpp);
  bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetter.class.getName(),
      new RootBeanDefinition(DefaultPublicPersistenceUnitSetter.class));
  bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName(),
      new RootBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class));
  DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter)
      bf.getBean(DefaultPublicPersistenceUnitSetter.class.getName());
  DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson)
      bf.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName());
  assertSame(mockEmf, bean.emf);
  assertSame(mockEmf2, bean2.emf);
}
origin: spring-projects/spring-framework

@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
  InjectionMetadata metadata = findPersistenceMetadata(beanName, bean.getClass(), pvs);
  try {
    metadata.inject(bean, beanName, pvs);
  }
  catch (Throwable ex) {
    throw new BeanCreationException(beanName, "Injection of persistence dependencies failed", ex);
  }
  return pvs;
}
origin: spring-projects/spring-framework

/**
 * Return a specified persistence unit for the given unit name,
 * as defined through the "persistenceUnits" map.
 * @param unitName the name of the persistence unit
 * @return the corresponding EntityManagerFactory,
 * or {@code null} if none found
 * @see #setPersistenceUnits
 */
@Nullable
protected EntityManagerFactory getPersistenceUnit(@Nullable String unitName) {
  if (this.persistenceUnits != null) {
    String unitNameForLookup = (unitName != null ? unitName : "");
    if (unitNameForLookup.isEmpty()) {
      unitNameForLookup = this.defaultPersistenceUnitName;
    }
    String jndiName = this.persistenceUnits.get(unitNameForLookup);
    if (jndiName == null && "".equals(unitNameForLookup) && this.persistenceUnits.size() == 1) {
      jndiName = this.persistenceUnits.values().iterator().next();
    }
    if (jndiName != null) {
      try {
        return lookup(jndiName, EntityManagerFactory.class);
      }
      catch (Exception ex) {
        throw new IllegalStateException("Could not obtain EntityManagerFactory [" + jndiName + "] from JNDI", ex);
      }
    }
  }
  return null;
}
origin: spring-projects/spring-framework

@Test
public void testSinglePersistenceUnitFromJndi() {
  Map<String, String> persistenceUnits = new HashMap<>();
  persistenceUnits.put("Person", "pu1");
  ExpectedLookupTemplate jt = new ExpectedLookupTemplate();
  jt.addObject("java:comp/env/pu1", mockEmf);
  DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
  PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
  bpp.setPersistenceUnits(persistenceUnits);
  bpp.setJndiTemplate(jt);
  bf.addBeanPostProcessor(bpp);
  bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetter.class.getName(),
      new RootBeanDefinition(DefaultPublicPersistenceUnitSetter.class));
  bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName(),
      new RootBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class));
  DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter)
      bf.getBean(DefaultPublicPersistenceUnitSetter.class.getName());
  DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson)
      bf.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName());
  assertSame(mockEmf, bean.emf);
  assertSame(mockEmf, bean2.emf);
}
origin: org.kuali.student.core/ks-common-test

  @Override
  public void postProcessBeanFactory(
      ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String[] classes = daoImplClasses.split(",");
    BeanDefinitionRegistry registry = ((BeanDefinitionRegistry) beanFactory);
    PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor();
    if (classes != null && classes.length > 0) {
      for (String line : classes) {
        if (!"".equals(line)) {
          try {
            String[] split = line.split("\\|");
            String className = split[0];
            Class<?> clazz = Class.forName(className);
            BeanDefinition definition = new RootBeanDefinition(
                clazz);
            registry.registerBeanDefinition(clazz.getSimpleName(),
                definition);
            pabpp.postProcessMergedBeanDefinition(
                (RootBeanDefinition) definition, clazz, clazz
                    .getSimpleName());

          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        }
      }
    }
  }
}
origin: spring-projects/spring-framework

private EntityManager resolveEntityManager(@Nullable String requestingBeanName) {
  // Obtain EntityManager reference from JNDI?
  EntityManager em = getPersistenceContext(this.unitName, false);
  if (em == null) {
    // No pre-built EntityManager found -> build one based on factory.
    // Obtain EntityManagerFactory from JNDI?
    EntityManagerFactory emf = getPersistenceUnit(this.unitName);
    if (emf == null) {
      // Need to search for EntityManagerFactory beans.
      emf = findEntityManagerFactory(this.unitName, requestingBeanName);
    }
    // Inject a shared transactional EntityManager proxy.
    if (emf instanceof EntityManagerFactoryInfo &&
        ((EntityManagerFactoryInfo) emf).getEntityManagerInterface() != null) {
      // Create EntityManager based on the info's vendor-specific type
      // (which might be more specific than the field's type).
      em = SharedEntityManagerCreator.createSharedEntityManager(
          emf, this.properties, this.synchronizedWithTransaction);
    }
    else {
      // Create EntityManager based on the field's type.
      em = SharedEntityManagerCreator.createSharedEntityManager(
          emf, this.properties, this.synchronizedWithTransaction, getResourceType());
    }
  }
  return em;
}
origin: spring-projects/spring-framework

PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
bpp.setPersistenceContexts(persistenceContexts);
bpp.setExtendedPersistenceContexts(extendedPersistenceContexts);
bpp.setDefaultPersistenceUnitName("System");
bpp.setJndiTemplate(jt);
bf.addBeanPostProcessor(bpp);
bf.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(),
origin: spring-projects/spring-framework

@Test
public void testSetterOfWrongTypeAnnotatedWithPersistenceUnit() {
  PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor();
  try {
    pabpp.postProcessProperties(null, new SetterOfWrongTypeAnnotatedWithPersistenceUnit(), "bean");
    fail("Can't inject this setter");
  }
  catch (IllegalStateException ex) {
    // Ok
  }
}
origin: org.springframework/spring-orm

private EntityManagerFactory resolveEntityManagerFactory(@Nullable String requestingBeanName) {
  // Obtain EntityManagerFactory from JNDI?
  EntityManagerFactory emf = getPersistenceUnit(this.unitName);
  if (emf == null) {
    // Need to search for EntityManagerFactory beans.
    emf = findEntityManagerFactory(this.unitName, requestingBeanName);
  }
  return emf;
}
origin: org.springframework/spring-orm

@Deprecated
@Override
public PropertyValues postProcessPropertyValues(
    PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
  return postProcessProperties(pvs, bean, beanName);
}
origin: spring-projects/spring-framework

@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
  InjectionMetadata metadata = findPersistenceMetadata(beanName, beanType, null);
  metadata.checkConfigMembers(beanDefinition);
}
origin: spring-projects/spring-framework

return lookup(jndiName, EntityManager.class);
org.springframework.orm.jpa.supportPersistenceAnnotationBeanPostProcessor

Javadoc

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

This post-processor will inject sub-interfaces of EntityManagerFactoryand 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 @PersistenceContextwith 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 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 org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBeanwill be used for setting up such EntityManagerFactory beans. Alternatively, such beans may also be obtained from JNDI, e.g. using the jee:jndi-lookupXML 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 #setPersistenceUnits, 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 org.springframework.transaction.jta.JtaTransactionManager as backend).

If you prefer the Java EE server's own EntityManager handling, specify entries in this post-processor's #setPersistenceContexts(or #setExtendedPersistenceContexts, 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.

Most used methods

  • <init>
  • buildPersistenceMetadata
  • findDefaultEntityManagerFactory
    Find a single default EntityManagerFactory in the Spring application context.
  • findEntityManagerFactory
    Find an EntityManagerFactory with the given name in the current Spring application context, falling
  • findNamedEntityManagerFactory
    Find an EntityManagerFactory with the given name in the current Spring application context.
  • findPersistenceMetadata
  • getPersistenceContext
    Return a specified persistence context for the given unit name, as defined through the "persistenceC
  • getPersistenceUnit
    Return a specified persistence unit for the given unit name, as defined through the "persistenceUnit
  • lookup
    Perform a JNDI lookup for the given resource by name.Called for EntityManagerFactory and EntityManag
  • postProcessProperties
  • postProcessMergedBeanDefinition
  • setDefaultPersistenceUnitName
    Specify the default persistence unit name, to be used in case of no unit name specified in an @Persi
  • postProcessMergedBeanDefinition,
  • setDefaultPersistenceUnitName,
  • setExtendedPersistenceContexts,
  • setJndiTemplate,
  • setPersistenceContexts,
  • setPersistenceUnits

Popular in Java

  • Updating database using SQL prepared statement
  • startActivity (Activity)
  • getApplicationContext (Context)
  • notifyDataSetChanged (ArrayAdapter)
  • FileReader (java.io)
    A specialized Reader that reads from a file in the file system. All read requests made by calling me
  • SimpleDateFormat (java.text)
    Formats and parses dates in a locale-sensitive manner. Formatting turns a Date into a String, and pa
  • HashSet (java.util)
    HashSet is an implementation of a Set. All optional operations (adding and removing) are supported.
  • NoSuchElementException (java.util)
    Thrown when trying to retrieve an element past the end of an Enumeration or Iterator.
  • JButton (javax.swing)
  • Logger (org.apache.log4j)
    This is the central class in the log4j package. Most logging operations, except configuration, are d
  • Top plugins for WebStorm
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now