@Override public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) { if (persistenceUnitProperties != null) { String puName = pui.getPersistenceUnitName() + "."; Set<String> keys = persistenceUnitProperties.keySet(); Properties props = pui.getProperties(); for (String key : keys) { if (key.startsWith(puName)){ String value = persistenceUnitProperties.get(key); String newKey = key.substring(puName.length()); if ("null".equalsIgnoreCase(value)){ props.remove(newKey); } else if (value != null && ! "".equals(value)) { props.put(newKey, value); } } } pui.setProperties(props); } }
/** * Show PUI infos * * @param pui * PersistenceUnitInfo */ private void dumpPersistenceUnitInfo( MutablePersistenceUnitInfo pui ) { _Log.debug( "Dumping content for PersistenceUnitInfo of " + pui.getPersistenceUnitName( ) ); _Log.debug( "** getTransactionType : " + pui.getTransactionType( ) ); _Log.debug( "** getPersistenceProviderClassName : " + pui.getPersistenceProviderClassName( ) ); _Log.debug( "** getPersistenceProviderPackageName : " + pui.getPersistenceProviderPackageName( ) ); _Log.debug( "** getPersistenceUnitName : " + pui.getPersistenceUnitName( ) ); _Log.debug( "** getPersistenceXMLSchemaVersion : " + pui.getPersistenceXMLSchemaVersion( ) ); _Log.debug( "** getJtaDataSource : " + pui.getJtaDataSource( ) ); _Log.debug( "** getManagedClassNames : " + pui.getManagedClassNames( ) ); _Log.debug( "** getMappingFileNames : " + pui.getMappingFileNames( ) ); _Log.debug( "** getNonJtaDataSource : " + pui.getNonJtaDataSource( ) ); _Log.debug( "** getPersistenceUnitRootUrl :" + pui.getPersistenceUnitRootUrl( ) ); _Log.debug( "** getProperties : " + pui.getProperties( ) ); }
@Test public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception { Object testEntity = new Object(); // This one's for the tx (shared) EntityManager sharedEm = mock(EntityManager.class); given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction()); // This is the application-specific one EntityManager mockEm = mock(EntityManager.class); given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm); LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo()); pui.setTransactionType(PersistenceUnitTransactionType.JTA); JpaTransactionManager jpatm = new JpaTransactionManager(); jpatm.setEntityManagerFactory(cefb.getObject()); TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute()); EntityManagerFactory emf = cefb.getObject(); assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject()); assertNotSame("EMF must be proxied", mockEmf, emf); EntityManager em = emf.createEntityManager(); em.joinTransaction(); assertFalse(em.contains(testEntity)); jpatm.commit(txStatus); cefb.destroy(); verify(mockEm).joinTransaction(); verify(mockEm).contains(testEntity); verify(mockEmf).close(); }
@Override protected void postProcessPersistenceUnitInfo(final MutablePersistenceUnitInfo pu) { super.postProcessPersistenceUnitInfo(pu); final Set<Class<?>> entityClasses = PersistenceProperties.getPersistenceUnitContext(pu.getPersistenceUnitName()) .getEntityClasses(); for (final Class<?> entityClass : entityClasses) { pu.addManagedClassName(entityClass.getName()); } }
protected PersistenceUnitInfo getMergedUnit(String persistenceUnitName, MutablePersistenceUnitInfo newPU) { if (!mergedPus.containsKey(persistenceUnitName)) { PersistenceUnitInfo puiToStore = newPU; if (jpa2ApiPresent) { puiToStore = createPersistenceUnit(newPU); } mergedPus.put(persistenceUnitName, puiToStore); } return mergedPus.get(persistenceUnitName); }
/** * {@inheritDoc} */ @Override public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) { pui.setExcludeUnlistedClasses(DEFAULT_EXCLUDE_UNLISTED_CLASSES); processConverterPackages(pui); for (String managedClassName : getManagedClassNames()) { pui.addManagedClassName(managedClassName); } }
@Override public void postProcessPersistenceUnitInfo( final MutablePersistenceUnitInfo mpui) { if (locations.length == 0) { LOG.warn("No locations provided"); } CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory(); try { for (String location : locations) { for (Resource resource : resResolver.getResources(location)) { MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader( resource); if (metadataReader.getAnnotationMetadata(). isAnnotated(Entity.class.getName())) { mpui.addManagedClassName( metadataReader.getClassMetadata(). getClassName()); } } } mpui.setExcludeUnlistedClasses(true); } catch (IOException e) { throw new RuntimeException(e); } }
@Override public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo unit) { /* unit.addProperty("hibernate.connection.username", getDbUser()); unit.addProperty("hibernate.connection.password", getDbPassword()); String jdbcUrl = String.format("jdbc:mysql://%s/%s", getDbHost(), getDbName()); unit.addProperty("hibernate.connection.url", jdbcUrl); unit.addProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver"); unit.addProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect"); unit.addProperty("org.jboss.logging.provider", "log4j2"); */ }
@Override public void postProcessPersistenceUnitInfo(final MutablePersistenceUnitInfo pui) { ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class)); for (BeanDefinition bd : scanner.findCandidateComponents(AbstractEntity.class.getPackage().getName())) { LOG.debug("Adding JPA entity {}", bd.getBeanClassName()); pui.addManagedClassName(bd.getBeanClassName()); } }
/** * Scans for *.orm.xml and adds Entites from classpath. * * @param pui * the pui */ @Override public void postProcessPersistenceUnitInfo( MutablePersistenceUnitInfo pui ) { _Log.info( "Scanning for JPA orm.xml files" ); for ( File ormFile : getListORMFiles( ) ) { String ormAbsolutePath = ormFile.getAbsolutePath( ); _Log.info( "Found ORM file : " + ormAbsolutePath ); pui.addMappingFileName( ormAbsolutePath.substring( ormAbsolutePath.indexOf( CLASSPATH_PATH_IDENTIFIER ) ) ); } _Log.info( "Scanning for JPA entities..." ); Set<String> entityClasses = AnnotationUtil.find( Entity.class.getName( ) ); entityClasses.addAll( AnnotationUtil.find( Embeddable.class.getName( ) ) ); entityClasses.addAll( AnnotationUtil.find( MappedSuperclass.class.getName( ) ) ); for ( String strClass : entityClasses ) { _Log.info( "Found entity class : " + strClass ); if ( !pui.getManagedClassNames( ).contains( strClass ) ) { pui.addManagedClassName( strClass ); } } if ( _Log.isDebugEnabled( ) ) { dumpPersistenceUnitInfo( pui ); } }
@Override public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo puInfo) { LOG.trace("Entering postProcessPersistenceUnitInfo"); puInfo.setTransactionType(PersistenceUnitTransactionType.JTA); puInfo.setJtaDataSource(jtaDataSource); puInfo.setNonJtaDataSource(nonJtaDataSource); LOG.trace("Exiting postProcessPersistenceUnitInfo: " + puInfo); }
public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo mutablePersistenceUnitInfo) { mutablePersistenceUnitInfo.setJtaDataSource(getJtaDataSource()); addKRADManagedClassNames(mutablePersistenceUnitInfo); if (mutablePersistenceUnitInfo.getPersistenceUnitName().equals(KRAD_APPLICATION_PERSISTENCE_UNIT_NAME) || mutablePersistenceUnitInfo.getPersistenceUnitName().equals( KRAD_SERVER_PERSISTENCE_UNIT_NAME)) { addRiceManagedClassNamesToKRADPersistenceUnit(mutablePersistenceUnitInfo); } }
/** * Adds the class names listed by exposed by the given exposer into the persistence unit * * @param mutablePersistenceUnitInfo the persistence unit to add managed JPA entity class names to * @param exposer the exposer for class names to manage */ public void addManagedClassNames(MutablePersistenceUnitInfo mutablePersistenceUnitInfo, PersistableBusinessObjectClassExposer exposer) { for (String exposedClassName : exposer.exposePersistableBusinessObjectClassNames()) { if (LOG.isDebugEnabled()) { LOG.debug("JPA will now be managing class: "+exposedClassName); } mutablePersistenceUnitInfo.addManagedClassName(exposedClassName); } }
private void build(List<Class> entities) { // Add new entities if not exists if (entities != null) { MutablePersistenceUnitInfo mutablePersistenceUnitInfo = (MutablePersistenceUnitInfo) info; for (Class entity : entities) { mutablePersistenceUnitInfo.addManagedClassName(entity.getName()); } } entityManagerFactory = Bootstrap.getEntityManagerFactoryBuilder(info, properties).build(); }
@Override public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) { List<String> moduleConfigs = null; try { moduleConfigs = ModuleUtils.getModuleEntries(MODULES_PKGNAME); } catch (IOException e) { throw new IllegalStateException("Problem fetching Hibernate jPOS modules", e); } for (String moduleConfig : moduleConfigs) { SAXReader reader = new SAXReader(); final URL url = getClass().getClassLoader().getResource(moduleConfig); assert url != null; final Document doc; try { doc = reader.read(url); } catch (DocumentException e) { throw new IllegalStateException("Could not initalize module reader", e); } Element module = doc.getRootElement().element("mappings"); if (module == null) { throw new IllegalStateException("No 'mappings' element in module=" + moduleConfig); } for (Iterator l = module.elementIterator("mapping"); l.hasNext(); ) { Element mapping = (Element) l.next(); final String resource = mapping.attributeValue("resource"); final String clazz = mapping.attributeValue("class"); if (resource != null) { if (!pui.getMappingFileNames().contains(resource)) { pui.addMappingFileName(resource); } } else if (clazz != null) { if (!pui.getManagedClassNames().contains(clazz)) { pui.addManagedClassName(clazz); } } else { throw new IllegalStateException("<mapping> element in configuration specifies no known " + "attributes at module " + moduleConfig); } } } }
/** * Determines whether the managed classes contain {@link Converter} annotations and adds them if necessary. * * @param pui the list of current list of managed classes. */ private void processConverterPackages(MutablePersistenceUnitInfo pui) { if (converterPackageNames != null) { for (String converterPackage : converterPackageNames) { // Code below lifted and modified from Spring's DefaultPersistenceUnitManager try { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(converterPackage) + ENTITY_CLASS_RESOURCE_PATTERN; if (LOG.isInfoEnabled()) { LOG.info(getPersistenceUnitName() + ": Scanning for JPA @Converter annotations in: " + pattern); } Resource[] resources = this.resourcePatternResolver.getResources(pattern); MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory( this.resourcePatternResolver); for (Resource resource : resources) { if (!resource.isReadable()) { continue; } if (LOG.isDebugEnabled()) { LOG.debug(getPersistenceUnitName() + ": Found Matching Resource: " + resource); } MetadataReader reader = readerFactory.getMetadataReader(resource); String className = reader.getClassMetadata().getClassName(); if (!pui.getManagedClassNames().contains(className) && converterAnnotationTypeFilter.match(reader, readerFactory)) { pui.addManagedClassName(className); if (LOG.isDebugEnabled()) { LOG.debug(getPersistenceUnitName() + ": Registering Converter in JPA Persistence Unit: " + className); } } } } catch (IOException ex) { throw new PersistenceException("Failed to scan classpath converters in package: " + converterPackage, ex); } } } }
@Override public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) { pui.getManagedClassNames().add(TestEntity3.class.getName()); }
public MutablePersistenceUnitInfo createUnit(Class<? extends Annotation> qualifier, String unitName) { ClassLoader classLoader = holder.getCurrentReloadableClassLoader(); MutablePersistenceUnitInfo result = new MutablePersistenceUnitInfo(); result.setExcludeUnlistedClasses(true); result.setValidationMode(ValidationMode.NONE); result.setPersistenceUnitName(unitName); result.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE); try { result.setPersistenceUnitRootUrl(new URL("http://foo.foo")); } catch (MalformedURLException e) { throw new RuntimeException(e); } result.addProperty(PersistenceUnitProperties.SESSION_CUSTOMIZER, CompositeSessionCustomizer.class.getName()); // search for entities { Set<Class<?>> jpaAnnotations = new HashSet<>( Arrays.asList(Entity.class, MappedSuperclass.class, Embeddable.class)); for (ClassNode classNode : index.getAllNodes()) { String className = Type.getObjectType(classNode.name).getClassName(); if (classNode.visibleAnnotations == null) continue; boolean jpaAnnotationFound = false; for (AnnotationNode annotation : classNode.visibleAnnotations) { Class<?> annotationClass = AsmUtil.loadClass(Type.getType(annotation.desc), classLoader); // test if the annotation is one of the jpa annotations if (jpaAnnotations.contains(annotationClass)) jpaAnnotationFound = true; } if (jpaAnnotationFound && isPartOfPU(classNode, qualifier, classLoader)) { result.addManagedClassName(className); } } } // search converters { index.getAllChildren(AttributeConverter.class).stream() .filter(node -> isPartOfPU(node, qualifier, classLoader)) .map(node -> AsmUtil.loadClass(Type.getObjectType(node.name), classLoader)).forEach(cls -> { Converter converter = cls.getAnnotation(Converter.class); if (converter != null && converter.autoApply()) result.addManagedClassName(cls.getName()); }); } return result; }
protected MutablePersistenceUnitInfo getMergedUnit(String persistenceUnitName, MutablePersistenceUnitInfo newPU) { if (!mergedPus.containsKey(persistenceUnitName)) { mergedPus.put(persistenceUnitName, newPU); } return (MutablePersistenceUnitInfo) mergedPus.get(persistenceUnitName); }
@Override protected void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo newPU) { super.postProcessPersistenceUnitInfo(newPU); ConfigurationOnlyState state = ConfigurationOnlyState.getState(); String persistenceUnitName = newPU.getPersistenceUnitName(); MutablePersistenceUnitInfo pui = getMergedUnit(persistenceUnitName, newPU); List<String> managedClassNames = newPU.getManagedClassNames(); for (String managedClassName : managedClassNames){ if (!pui.getManagedClassNames().contains(managedClassName)) { pui.addManagedClassName(managedClassName); } } List<String> mappingFileNames = newPU.getMappingFileNames(); for (String mappingFileName : mappingFileNames) { if (!pui.getMappingFileNames().contains(mappingFileName)) { pui.addMappingFileName(mappingFileName); } } pui.setExcludeUnlistedClasses(newPU.excludeUnlistedClasses()); for (URL url : newPU.getJarFileUrls()) { // Avoid duplicate class scanning by Ejb3Configuration. Do not re-add the URL to the list of jars for this // persistence unit or duplicate the persistence unit root URL location (both types of locations are scanned) if (!pui.getJarFileUrls().contains(url) && !pui.getPersistenceUnitRootUrl().equals(url)) { pui.addJarFileUrl(url); } } if (pui.getProperties() == null) { pui.setProperties(newPU.getProperties()); } else { Properties props = newPU.getProperties(); if (props != null) { for (Object key : props.keySet()) { pui.getProperties().put(key, props.get(key)); for (BroadleafClassTransformer transformer : classTransformers) { try { transformer.compileJPAProperties(props, key); } catch (Exception e) { throw new RuntimeException(e); } } } } } if (state == null || !state.isConfigurationOnly()) { if (newPU.getJtaDataSource() != null) { pui.setJtaDataSource(newPU.getJtaDataSource()); } if (newPU.getNonJtaDataSource() != null) { pui.setNonJtaDataSource(newPU.getNonJtaDataSource()); } } else { pui.getProperties().setProperty("hibernate.hbm2ddl.auto", "none"); pui.getProperties().setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false"); } pui.setTransactionType(newPU.getTransactionType()); if (newPU.getPersistenceProviderClassName() != null) { pui.setPersistenceProviderClassName(newPU.getPersistenceProviderClassName()); } if (newPU.getPersistenceProviderPackageName() != null) { pui.setPersistenceProviderPackageName(newPU.getPersistenceProviderPackageName()); } }
public void addRiceManagedClassNamesToKRADPersistenceUnit(MutablePersistenceUnitInfo mutablePersistenceUnitInfo) { addManagedClassNames(mutablePersistenceUnitInfo, new RiceToNervousSystemBusinessObjectClassExposer()); }
/** * enrich the PersistenceUnitInfo read from the persistence.xml configuration file with a reference * to the jtaDataSource injected via the Spring configuration. the JTA capable datasource is then * used by the LocalContainerEntityManagerFactoryBean to create the EntityManagerFactory * * @see PersistenceUnitPostProcessor#postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo) */ public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo mutablePersistenceUnitInfo) { mutablePersistenceUnitInfo.setJtaDataSource(getJtaDataSource()); }
/** * * Adds all the KNS Managed entities to the persistence unit - which is important, becuase all * persistence units get the KNS entities to manage * * @param mutablePersistenceUnitInfo */ public void addKRADManagedClassNames(MutablePersistenceUnitInfo mutablePersistenceUnitInfo) { addManagedClassNames(mutablePersistenceUnitInfo, new KRADPersistableBusinessObjectClassExposer()); }
/** * Called when creating the persistence unit. Override to customize. No need * to call super() */ protected void customizePersistenceUnit(MutablePersistenceUnitInfo unit) { }