org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor Java Examples

The following examples show how to use org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PersistenceUnitsHolder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static Map<String, RecordedState> constructMetadataAdvance(
        final List<PersistenceUnitDescriptor> parsedPersistenceXmlDescriptors, Scanner scanner,
        Collection<Class<? extends Integrator>> additionalIntegrators,
        PreGeneratedProxies proxyClassDefinitions,
        MultiTenancyStrategy strategy) {
    Map<String, RecordedState> recordedStates = new HashMap<>();

    for (PersistenceUnitDescriptor unit : parsedPersistenceXmlDescriptors) {
        RecordedState m = createMetadata(unit, scanner, additionalIntegrators, proxyClassDefinitions, strategy);
        Object previous = recordedStates.put(unitName(unit), m);
        if (previous != null) {
            throw new IllegalStateException("Duplicate persistence unit name: " + unit.getName());
        }
    }

    return recordedStates;
}
 
Example #2
Source File: FastBootMetadataBuilder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void applyTransactionProperties(PersistenceUnitDescriptor persistenceUnit,
        Map<String, Object> configurationValues) {
    PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionTypeHelper
            .interpretTransactionType(configurationValues.get(JPA_TRANSACTION_TYPE));
    if (transactionType == null) {
        transactionType = persistenceUnit.getTransactionType();
    }
    if (transactionType == null) {
        // is it more appropriate to have this be based on bootstrap entry point (EE vs SE)?
        transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
    }
    boolean hasTransactionStrategy = configurationValues.containsKey(TRANSACTION_COORDINATOR_STRATEGY);
    if (hasTransactionStrategy) {
        LOG.overridingTransactionStrategyDangerous(TRANSACTION_COORDINATOR_STRATEGY);
    } else {
        if (transactionType == PersistenceUnitTransactionType.JTA) {
            configurationValues.put(TRANSACTION_COORDINATOR_STRATEGY,
                    JtaTransactionCoordinatorBuilderImpl.class);
        } else if (transactionType == PersistenceUnitTransactionType.RESOURCE_LOCAL) {
            configurationValues.put(TRANSACTION_COORDINATOR_STRATEGY,
                    JdbcResourceLocalTransactionCoordinatorBuilderImpl.class);
        }
    }
}
 
Example #3
Source File: LightPersistenceXmlDescriptor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void verifyIgnoredFields(final PersistenceUnitDescriptor toClone) {
    if (toClone.getNonJtaDataSource() != null) {
        throw new UnsupportedOperationException("Value found for #getNonJtaDataSource : not supported yet");
    }
    // This one needs to be ignored:
    // if ( toClone.getPersistenceUnitRootUrl() != null ) {
    // throw new UnsupportedOperationException( "Value found for
    // #getPersistenceUnitRootUrl : not supported yet" );
    // }
    if (toClone.getMappingFileNames() != null && !toClone.getMappingFileNames().isEmpty()) {
        throw new UnsupportedOperationException("Value found for #getMappingFileNames : not supported yet");
    }
    if (toClone.getJarFileUrls() != null && !toClone.getJarFileUrls().isEmpty()) {
        throw new UnsupportedOperationException("Value found for #getJarFileUrls : not supported yet");
    }
    if (toClone.getJtaDataSource() != null) {
        throw new UnsupportedOperationException("Value found for #getJtaDataSource : not supported yet");
    }
    if (toClone.getNonJtaDataSource() != null) {
        throw new UnsupportedOperationException("Value found for #getNonJtaDataSource : not supported");
    }
}
 
Example #4
Source File: FastBootHibernatePersistenceProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public static String extractRequestedProviderName(PersistenceUnitDescriptor persistenceUnit, Map integration) {
    final String integrationProviderName = extractProviderName(integration);
    if (integrationProviderName != null) {
        log.debugf("Integration provided explicit PersistenceProvider [%s]", integrationProviderName);
        return integrationProviderName;
    }

    final String persistenceUnitRequestedProvider = extractProviderName(persistenceUnit);
    if (persistenceUnitRequestedProvider != null) {
        log.debugf("Persistence-unit [%s] requested PersistenceProvider [%s]", persistenceUnit.getName(),
                persistenceUnitRequestedProvider);
        return persistenceUnitRequestedProvider;
    }

    // NOTE : if no provider requested we assume we are the provider (the calls got
    // to us somehow...)
    log.debug("No PersistenceProvider explicitly requested, assuming Hibernate");
    return FastBootHibernatePersistenceProvider.class.getName();
}
 
Example #5
Source File: FastBootHibernateReactivePersistenceProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public EntityManagerFactory createEntityManagerFactory(String emName, Map properties) {
    if (properties == null)
        properties = new HashMap<Object, Object>();
    try {
        // These are pre-parsed during image generation:
        final List<PersistenceUnitDescriptor> units = PersistenceUnitsHolder.getPersistenceUnitDescriptors();

        for (PersistenceUnitDescriptor unit : units) {
            //if the provider is not set, don't use it as people might want to use Hibernate ORM
            if (IMPLEMENTATION_NAME.equalsIgnoreCase(unit.getProviderClassName()) ||
                    unit.getProviderClassName() == null) {
                EntityManagerFactoryBuilder emfBuilder = getEntityManagerFactoryBuilderOrNull(emName, properties);
                EntityManagerFactory emf = emfBuilder.build();
                return emf;
            }
        }

        //not the right provider
        return null;
    } catch (PersistenceException pe) {
        throw pe;
    } catch (Exception e) {
        throw new PersistenceException("Unable to build EntityManagerFactory", e);
    }
}
 
Example #6
Source File: ReactiveProviderChecker.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Extract the requested persistence provider name using the algorithm Hibernate uses.  Namely, a provider named
 * in the 'integration' map (under the key '{@value Settings#JPA_PERSISTENCE_PROVIDER}') is preferred, as per-spec,
 * over value specified in persistence unit.
 *
 * @param persistenceUnit The {@code <persistence-unit/>} descriptor.
 * @param integration The integration values.
 *
 * @return The extracted provider name, or {@code null} if none found.
 */
public static String extractRequestedProviderName(PersistenceUnitDescriptor persistenceUnit, Map integration) {
    final String integrationProviderName = extractProviderName( integration );
    if ( integrationProviderName != null ) {
        log.debugf( "Integration provided explicit PersistenceProvider [%s]", integrationProviderName );
        return integrationProviderName;
    }

    final String persistenceUnitRequestedProvider = extractProviderName( persistenceUnit );
    if ( persistenceUnitRequestedProvider != null ) {
        log.debugf(
                "Persistence-unit [%s] requested PersistenceProvider [%s]",
                persistenceUnit.getName(),
                persistenceUnitRequestedProvider
        );
        return persistenceUnitRequestedProvider;
    }

    // NOTE : if no provider requested we assume we are NOT the provider, leaving the responsibility to Hibernate ORM
    // (the classical, blocking version)
    log.debug( "No PersistenceProvider explicitly requested" );
    return null;
}
 
Example #7
Source File: Helper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static PersistenceException persistenceException(
		PersistenceUnitDescriptor persistenceUnit,
		String message,
		Exception cause) {
	return new PersistenceException(
			getExceptionHeader( persistenceUnit ) + message,
			cause
	);
}
 
Example #8
Source File: StandardJpaScanEnvironmentImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public StandardJpaScanEnvironmentImpl(PersistenceUnitDescriptor persistenceUnitDescriptor) {
	this.persistenceUnitDescriptor = persistenceUnitDescriptor;

	this.explicitlyListedClassNames = persistenceUnitDescriptor.getManagedClassNames() == null
			? Collections.<String>emptyList()
			: persistenceUnitDescriptor.getManagedClassNames();
	this.explicitlyListedMappingFiles = persistenceUnitDescriptor.getMappingFileNames() == null
			? Collections.<String>emptyList()
			: persistenceUnitDescriptor.getMappingFileNames();
}
 
Example #9
Source File: PersistenceUnitsHolder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static List<PersistenceUnitDescriptor> convertPersistenceUnits(
        final List<ParsedPersistenceXmlDescriptor> parsedPersistenceXmlDescriptors) {
    try {
        return parsedPersistenceXmlDescriptors.stream().map(LightPersistenceXmlDescriptor::new)
                .collect(Collectors.toList());
    } catch (Exception e) {
        throw new PersistenceException("Unable to locate persistence units", e);
    }
}
 
Example #10
Source File: PersistenceUnitsHolder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static String unitName(PersistenceUnitDescriptor unit) {
    String name = unit.getName();
    if (name == null) {
        return NO_NAME_TOKEN;
    }
    return name;
}
 
Example #11
Source File: PersistenceUnitsHolder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static RecordedState createMetadata(PersistenceUnitDescriptor unit, Scanner scanner,
        Collection<Class<? extends Integrator>> additionalIntegrators, PreGeneratedProxies proxyDefinitions,
        MultiTenancyStrategy strategy) {
    FastBootMetadataBuilder fastBootMetadataBuilder = new FastBootMetadataBuilder(unit, scanner, additionalIntegrators,
            proxyDefinitions, strategy);
    return fastBootMetadataBuilder.build();
}
 
Example #12
Source File: LightPersistenceXmlDescriptor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public LightPersistenceXmlDescriptor(final PersistenceUnitDescriptor toClone) {
    this.name = toClone.getName();
    this.providerClassName = toClone.getProviderClassName();
    this.useQuotedIdentifiers = toClone.isUseQuotedIdentifiers();
    this.transactionType = toClone.getTransactionType();
    this.validationMode = toClone.getValidationMode();
    this.sharedCachemode = toClone.getSharedCacheMode();
    this.managedClassNames = Collections.unmodifiableList(toClone.getManagedClassNames());
    this.properties = toClone.getProperties();
    verifyIgnoredFields(toClone);
}
 
Example #13
Source File: FastBootHibernatePersistenceProvider.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private boolean isProvider(PersistenceUnitDescriptor persistenceUnit) {
    Map<Object, Object> props = Collections.emptyMap();
    String requestedProviderName = extractRequestedProviderName(persistenceUnit, props);
    if (requestedProviderName == null) {
        // We'll always assume we are the best possible provider match unless the user
        // explicitly asks for a different one.
        return true;
    }
    return FastBootHibernatePersistenceProvider.class.getName().equals(requestedProviderName)
            || "org.hibernate.jpa.HibernatePersistenceProvider".equals(requestedProviderName);
}
 
Example #14
Source File: FastBootHibernateReactivePersistenceProvider.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private boolean isProvider(PersistenceUnitDescriptor persistenceUnit) {
    Map<Object, Object> props = Collections.emptyMap();
    String requestedProviderName = FastBootHibernatePersistenceProvider.extractRequestedProviderName(persistenceUnit,
            props);
    if (requestedProviderName == null) {
        // We'll always assume we are the best possible provider match unless the user
        // explicitly asks for a different one.
        return true;
    }
    return FastBootHibernateReactivePersistenceProvider.class.getName().equals(requestedProviderName)
            || IMPLEMENTATION_NAME.equals(requestedProviderName)
            || FastBootHibernatePersistenceProvider.class.getName().equals(requestedProviderName)
            || "org.hibernate.jpa.HibernatePersistenceProvider".equals(requestedProviderName);
}
 
Example #15
Source File: HibernatePersistenceProvider.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected EntityManagerFactoryBuilder getEntityManagerFactoryBuilder(PersistenceUnitDescriptor persistenceUnitDescriptor,
		Map integration, ClassLoader providedClassLoader) {
	return Bootstrap.getEntityManagerFactoryBuilder( persistenceUnitDescriptor, integration, providedClassLoader );
}
 
Example #16
Source File: EntityManagerFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public EntityManagerFactoryBuilderImpl(
		PersistenceUnitDescriptor persistenceUnit,
		Map integrationSettings,
		ClassLoaderService providedClassLoaderService ) {
	this( persistenceUnit, integrationSettings, null, providedClassLoaderService);
}
 
Example #17
Source File: LogHelper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static void logPersistenceUnitInformation(PersistenceUnitDescriptor descriptor) {
	if ( ! log.isDebugEnabled() ) {
		log.processingPersistenceUnitInfoName( descriptor.getName() );
		return;
	}

	StringBuilder sb = new StringBuilder();
	sb.append( "PersistenceUnitInfo [\n\t" )
			.append( "name: " )
			.append( descriptor.getName() )
			.append( "\n\t" )
			.append( "persistence provider classname: " )
			.append( descriptor.getProviderClassName() )
			.append( "\n\t" )
			.append( "classloader: " )
			.append( descriptor.getClassLoader() )
			.append( "\n\t" )
			.append( "excludeUnlistedClasses: " )
			.append( descriptor.isExcludeUnlistedClasses() )
			.append( "\n\t" )
			.append( "JTA datasource: " )
			.append( descriptor.getJtaDataSource() )
			.append( "\n\t" )
			.append( "Non JTA datasource: " )
			.append( descriptor.getNonJtaDataSource() )
			.append( "\n\t" )
			.append( "Transaction type: " )
			.append( descriptor.getTransactionType() )
			.append( "\n\t" )
			.append( "PU root URL: " )
			.append( descriptor.getPersistenceUnitRootUrl() )
			.append( "\n\t" )
			.append( "Shared Cache Mode: " )
			.append( descriptor.getSharedCacheMode() )
			.append( "\n\t" )
			.append( "Validation Mode: " )
			.append( descriptor.getValidationMode() )
			.append( "\n\t" );
	sb.append( "Jar files URLs [" );
	List<URL> jarFileUrls = descriptor.getJarFileUrls();
	if ( jarFileUrls != null ) {
		for ( URL url : jarFileUrls ) {
			sb.append( "\n\t\t" ).append( url );
		}
	}
	sb.append( "]\n\t" );
	sb.append( "Managed classes names [" );
	List<String> classNames = descriptor.getManagedClassNames();
	if ( classNames != null ) {
		for ( String className : classNames ) {
			sb.append( "\n\t\t" ).append( className );
		}
	}
	sb.append( "]\n\t" );
	sb.append( "Mapping files names [" );
	List<String> mappingFiles = descriptor.getMappingFileNames();
	if ( mappingFiles != null ) {
		for ( String file : mappingFiles ) {
			sb.append( "\n\t\t" ).append( file );
		}
	}
	sb.append( "]\n\t" );
	sb.append( "Properties [" );
	Properties properties = descriptor.getProperties();
	if (properties != null) {
		Enumeration names = properties.propertyNames();
		while ( names.hasMoreElements() ) {
			String name = (String) names.nextElement();
			sb.append( "\n\t\t" ).append( name ).append( ": " ).append( properties.getProperty( name ) );
		}
	}
	sb.append( "]" );

	log.debug( sb.toString() );
}
 
Example #18
Source File: HibernatePersistenceProvider.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected EntityManagerFactoryBuilder getEntityManagerFactoryBuilder(PersistenceUnitDescriptor persistenceUnitDescriptor,
		Map integration, ClassLoaderService providedClassLoaderService) {
	return Bootstrap.getEntityManagerFactoryBuilder( persistenceUnitDescriptor, integration, providedClassLoaderService );
}
 
Example #19
Source File: EntityManagerFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public EntityManagerFactoryBuilderImpl(PersistenceUnitDescriptor persistenceUnit, Map integrationSettings) {
	this( persistenceUnit, integrationSettings, null, null );
}
 
Example #20
Source File: EntityManagerFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public EntityManagerFactoryBuilderImpl(
		PersistenceUnitDescriptor persistenceUnit,
		Map integrationSettings,
		ClassLoader providedClassLoader ) {
	this( persistenceUnit, integrationSettings, providedClassLoader, null);
}
 
Example #21
Source File: FastBootHibernatePersistenceProvider.java    From quarkus with Apache License 2.0 4 votes vote down vote up
/**
 * Copied and modified from
 * HibernatePersistenceProvider#getEntityManagerFactoryBuilderOrNull(String,
 * Map, ClassLoader, ClassLoaderService) Notable changes: - ignore the
 * ClassLoaderService parameter to inject our own custom implementation instead
 * - verify the Map properties are not set (or fail as we can't support runtime
 * overrides) - don't try looking for ParsedPersistenceXmlDescriptor resources
 * to parse, just take the pre-parsed ones from the static final field - class
 * annotations metadata is also injected
 */
@SuppressWarnings("rawtypes")
private EntityManagerFactoryBuilder getEntityManagerFactoryBuilderOrNull(String persistenceUnitName,
        Map properties) {
    log.tracef("Attempting to obtain correct EntityManagerFactoryBuilder for persistenceUnitName : %s",
            persistenceUnitName);

    verifyProperties(properties);

    // These are pre-parsed during image generation:
    final List<PersistenceUnitDescriptor> units = PersistenceUnitsHolder.getPersistenceUnitDescriptors();

    log.debugf("Located %s persistence units; checking each", units.size());

    if (persistenceUnitName == null && units.size() > 1) {
        // no persistence-unit name to look for was given and we found multiple
        // persistence-units
        throw new PersistenceException("No name provided and multiple persistence units found");
    }

    for (PersistenceUnitDescriptor persistenceUnit : units) {
        log.debugf(
                "Checking persistence-unit [name=%s, explicit-provider=%s] against incoming persistence unit name [%s]",
                persistenceUnit.getName(), persistenceUnit.getProviderClassName(), persistenceUnitName);

        final boolean matches = persistenceUnitName == null
                || persistenceUnit.getName().equals(persistenceUnitName);
        if (!matches) {
            log.debugf("Excluding from consideration '%s' due to name mis-match", persistenceUnit.getName());
            continue;
        }

        // See if we (Hibernate) are the persistence provider
        if (!isProvider(persistenceUnit)) {
            log.debug("Excluding from consideration due to provider mis-match");
            continue;
        }

        RecordedState recordedState = PersistenceUnitsHolder.getRecordedState(persistenceUnitName);

        final PrevalidatedQuarkusMetadata metadata = recordedState.getMetadata();
        final BuildTimeSettings buildTimeSettings = recordedState.getBuildTimeSettings();
        final IntegrationSettings integrationSettings = recordedState.getIntegrationSettings();
        RuntimeSettings.Builder runtimeSettingsBuilder = new RuntimeSettings.Builder(buildTimeSettings,
                integrationSettings);

        // Inject the datasource
        injectDataSource(persistenceUnitName, runtimeSettingsBuilder);

        HibernateOrmIntegrations.contributeRuntimeProperties((k, v) -> runtimeSettingsBuilder.put(k, v));

        RuntimeSettings runtimeSettings = runtimeSettingsBuilder.build();

        StandardServiceRegistry standardServiceRegistry = rewireMetadataAndExtractServiceRegistry(
                runtimeSettings, recordedState);

        final Object cdiBeanManager = Arc.container().beanManager();
        final Object validatorFactory = Arc.container().instance("quarkus-hibernate-validator-factory").get();

        return new FastBootEntityManagerFactoryBuilder(
                metadata /* Uses the StandardServiceRegistry references by this! */,
                persistenceUnitName,
                standardServiceRegistry /* Mostly ignored! (yet needs to match) */,
                runtimeSettings,
                validatorFactory, cdiBeanManager, recordedState.getMultiTenancyStrategy());
    }

    log.debug("Found no matching persistence units");
    return null;
}
 
Example #22
Source File: EntityManagerFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private EntityManagerFactoryBuilderImpl(
		PersistenceUnitDescriptor persistenceUnit,
		Map integrationSettings,
		ClassLoader providedClassLoader,
		ClassLoaderService providedClassLoaderService) {

	LogHelper.logPersistenceUnitInformation( persistenceUnit );

	this.persistenceUnit = persistenceUnit;

	if ( integrationSettings == null ) {
		integrationSettings = Collections.emptyMap();
	}

	// Build the boot-strap service registry, which mainly handles class loader interactions
	final BootstrapServiceRegistry bsr = buildBootstrapServiceRegistry( integrationSettings, providedClassLoader, providedClassLoaderService);

	// merge configuration sources and build the "standard" service registry
	final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );
	final MergedSettings mergedSettings = mergeSettings( persistenceUnit, integrationSettings, ssrBuilder );
	this.configurationValues = mergedSettings.getConfigurationValues();

	// Build the "standard" service registry
	ssrBuilder.applySettings( configurationValues );
	configure( ssrBuilder );
	this.standardServiceRegistry = ssrBuilder.build();
	configure( standardServiceRegistry, mergedSettings );

	final MetadataSources metadataSources = new MetadataSources( bsr );
	List<AttributeConverterDefinition> attributeConverterDefinitions = populate(
			metadataSources,
			mergedSettings,
			standardServiceRegistry
	);
	this.metamodelBuilder = (MetadataBuilderImplementor) metadataSources.getMetadataBuilder( standardServiceRegistry );
	populate( metamodelBuilder, mergedSettings, standardServiceRegistry, attributeConverterDefinitions );

	// todo : would be nice to have MetadataBuilder still do the handling of CfgXmlAccessService here
	//		another option is to immediately handle them here (probably in mergeSettings?) as we encounter them...
	final CfgXmlAccessService cfgXmlAccessService = standardServiceRegistry.getService( CfgXmlAccessService.class );
	if ( cfgXmlAccessService.getAggregatedConfig() != null ) {
		if ( cfgXmlAccessService.getAggregatedConfig().getMappingReferences() != null ) {
			for ( MappingReference mappingReference : cfgXmlAccessService.getAggregatedConfig().getMappingReferences() ) {
				mappingReference.apply( metadataSources );
			}
		}
	}

	this.managedResources = MetadataBuildingProcess.prepare(
			metadataSources,
			metamodelBuilder.getBootstrapContext()
	);

	applyMetadataBuilderContributor();


	withValidatorFactory( configurationValues.get( org.hibernate.cfg.AvailableSettings.JPA_VALIDATION_FACTORY ) );

	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// push back class transformation to the environment; for the time being this only has any effect in EE
	// container situations, calling back into PersistenceUnitInfo#addClassTransformer

	final boolean dirtyTrackingEnabled = readBooleanConfigurationValue( AvailableSettings.ENHANCER_ENABLE_DIRTY_TRACKING );
	final boolean lazyInitializationEnabled = readBooleanConfigurationValue( AvailableSettings.ENHANCER_ENABLE_LAZY_INITIALIZATION );
	final boolean associationManagementEnabled = readBooleanConfigurationValue( AvailableSettings.ENHANCER_ENABLE_ASSOCIATION_MANAGEMENT );

	if ( dirtyTrackingEnabled || lazyInitializationEnabled || associationManagementEnabled ) {
		EnhancementContext enhancementContext = getEnhancementContext(
				dirtyTrackingEnabled,
				lazyInitializationEnabled,
				associationManagementEnabled
		);

		persistenceUnit.pushClassTransformer( enhancementContext );
	}

	// for the time being we want to revoke access to the temp ClassLoader if one was passed
	metamodelBuilder.applyTempClassLoader( null );
}
 
Example #23
Source File: Helper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static PersistenceException persistenceException(
		PersistenceUnitDescriptor persistenceUnit,
		String message) {
	return persistenceException( persistenceUnit, message, null );
}
 
Example #24
Source File: Helper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private static String getExceptionHeader(PersistenceUnitDescriptor persistenceUnit) {
	return "[PersistenceUnit: " + persistenceUnit.getName() + "] ";
}
 
Example #25
Source File: CustomDescriptor.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public CustomDescriptor(PersistenceUnitDescriptor descriptor, List<String> names) {
	this.descriptor = descriptor;
	this.names = names;
	this.names.addAll(U.safe(descriptor.getManagedClassNames()));
}
 
Example #26
Source File: FastBootHibernateReactivePersistenceProvider.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private EntityManagerFactoryBuilder getEntityManagerFactoryBuilderOrNull(String persistenceUnitName,
        Map properties) {
    log.tracef("Attempting to obtain correct EntityManagerFactoryBuilder for persistenceUnitName : %s",
            persistenceUnitName);

    verifyProperties(properties);

    // These are pre-parsed during image generation:
    final List<PersistenceUnitDescriptor> units = PersistenceUnitsHolder.getPersistenceUnitDescriptors();

    log.debugf("Located %s persistence units; checking each", units.size());

    if (persistenceUnitName == null && units.size() > 1) {
        // no persistence-unit name to look for was given and we found multiple
        // persistence-units
        throw new PersistenceException("No name provided and multiple persistence units found");
    }

    for (PersistenceUnitDescriptor persistenceUnit : units) {
        log.debugf(
                "Checking persistence-unit [name=%s, explicit-provider=%s] against incoming persistence unit name [%s]",
                persistenceUnit.getName(), persistenceUnit.getProviderClassName(), persistenceUnitName);

        final boolean matches = persistenceUnitName == null
                || persistenceUnit.getName().equals(persistenceUnitName);
        if (!matches) {
            log.debugf("Excluding from consideration '%s' due to name mis-match", persistenceUnit.getName());
            continue;
        }

        // See if we (Hibernate) are the persistence provider
        if (!isProvider(persistenceUnit)) {
            log.debug("Excluding from consideration due to provider mis-match");
            continue;
        }

        RecordedState recordedState = PersistenceUnitsHolder.getRecordedState(persistenceUnitName);

        final PrevalidatedQuarkusMetadata metadata = recordedState.getMetadata();
        final BuildTimeSettings buildTimeSettings = recordedState.getBuildTimeSettings();
        final IntegrationSettings integrationSettings = recordedState.getIntegrationSettings();
        RuntimeSettings.Builder runtimeSettingsBuilder = new RuntimeSettings.Builder(buildTimeSettings,
                integrationSettings);

        HibernateOrmIntegrations.contributeRuntimeProperties((k, v) -> runtimeSettingsBuilder.put(k, v));

        RuntimeSettings runtimeSettings = runtimeSettingsBuilder.build();

        StandardServiceRegistry standardServiceRegistry = rewireMetadataAndExtractServiceRegistry(
                runtimeSettings, recordedState, persistenceUnitName);

        final Object cdiBeanManager = Arc.container().beanManager();
        final Object validatorFactory = Arc.container().instance("quarkus-hibernate-validator-factory").get();

        return new FastBootReactiveEntityManagerFactoryBuilder(
                metadata /* Uses the StandardServiceRegistry references by this! */,
                persistenceUnitName,
                standardServiceRegistry /* Mostly ignored! (yet needs to match) */,
                runtimeSettings,
                validatorFactory, cdiBeanManager, recordedState.getMultiTenancyStrategy());
    }

    log.debug("Found no matching persistence units");
    return null;
}
 
Example #27
Source File: FastBootHibernatePersistenceProvider.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private static String extractProviderName(PersistenceUnitDescriptor persistenceUnit) {
    final String persistenceUnitRequestedProvider = persistenceUnit.getProviderClassName();
    return persistenceUnitRequestedProvider == null ? null : persistenceUnitRequestedProvider.trim();
}
 
Example #28
Source File: ReactivePersistenceProvider.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected EntityManagerFactoryBuilder getEntityManagerFactoryBuilder(PersistenceUnitDescriptor persistenceUnitDescriptor, Map integration) {
	return new ReactiveEntityManagerFactoryBuilder( persistenceUnitDescriptor, integration );
}
 
Example #29
Source File: FastBootMetadataBuilder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void addPUManagedClassNamesToMetadataSources(PersistenceUnitDescriptor persistenceUnit,
        MetadataSources metadataSources) {
    for (String className : persistenceUnit.getManagedClassNames()) {
        metadataSources.addAnnotatedClassName(className);
    }
}
 
Example #30
Source File: FastBootMetadataBuilder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public FastBootMetadataBuilder(final PersistenceUnitDescriptor persistenceUnit, Scanner scanner,
        Collection<Class<? extends Integrator>> additionalIntegrators, PreGeneratedProxies preGeneratedProxies,
        MultiTenancyStrategy strategy) {
    this.persistenceUnit = persistenceUnit;
    this.additionalIntegrators = additionalIntegrators;
    this.preGeneratedProxies = preGeneratedProxies;
    final ClassLoaderService providedClassLoaderService = FlatClassLoaderService.INSTANCE;

    // Copying semantics from: new EntityManagerFactoryBuilderImpl( unit,
    // integration, instance );
    // Except we remove support for several legacy features and XML binding
    final ClassLoader providedClassLoader = null;

    LogHelper.logPersistenceUnitInformation(persistenceUnit);

    // Build the boot-strap service registry, which mainly handles class loader
    // interactions
    final BootstrapServiceRegistry bsr = buildBootstrapServiceRegistry(providedClassLoaderService);

    // merge configuration sources and build the "standard" service registry
    final RecordableBootstrap ssrBuilder = new RecordableBootstrap(bsr);

    final MergedSettings mergedSettings = mergeSettings(persistenceUnit);
    this.buildTimeSettings = new BuildTimeSettings(mergedSettings.getConfigurationValues());

    // Build the "standard" service registry
    ssrBuilder.applySettings(buildTimeSettings.getSettings());
    this.standardServiceRegistry = ssrBuilder.build();
    registerIdentifierGenerators(standardServiceRegistry);

    this.providedServices = ssrBuilder.getProvidedServices();

    /**
     * This is required to properly integrate Hibernate Envers.
     *
     * The EnversService requires multiple steps to be properly built, the most important ones are:
     *
     * 1. The EnversServiceContributor contributes the EnversServiceInitiator to the RecordableBootstrap.
     * 2. After RecordableBootstrap builds a StandardServiceRegistry, the first time the EnversService is
     * requested, it is created by the initiator and configured by the registry.
     * 3. The MetadataBuildingProcess completes by calling the AdditionalJaxbMappingProducer which
     * initializes the EnversService and produces some additional mapping documents.
     * 4. After that point the EnversService appears to be fully functional.
     *
     * The following trick uses the aforementioned steps to setup the EnversService and then turns it into
     * a ProvidedService so that it is not necessary to repeat all these complex steps during the reactivation
     * of the destroyed service registry in PreconfiguredServiceRegistryBuilder.
     *
     */
    for (Class<? extends Service> postBuildProvidedService : ssrBuilder.getPostBuildProvidedServices()) {
        providedServices.add(new ProvidedService(postBuildProvidedService,
                standardServiceRegistry.getService(postBuildProvidedService)));
    }

    final MetadataSources metadataSources = new MetadataSources(bsr);
    addPUManagedClassNamesToMetadataSources(persistenceUnit, metadataSources);

    this.metamodelBuilder = (MetadataBuilderImplementor) metadataSources
            .getMetadataBuilder(standardServiceRegistry);
    if (scanner != null) {
        this.metamodelBuilder.applyScanner(scanner);
    }
    populate(metamodelBuilder, mergedSettings.cacheRegionDefinitions, standardServiceRegistry);

    this.managedResources = MetadataBuildingProcess.prepare(metadataSources,
            metamodelBuilder.getBootstrapContext());

    applyMetadataBuilderContributor();

    // BVAL integration:
    this.validatorFactory = withValidatorFactory(
            buildTimeSettings.get(org.hibernate.cfg.AvailableSettings.JPA_VALIDATION_FACTORY));

    // Unable to automatically handle:
    // AvailableSettings.ENHANCER_ENABLE_DIRTY_TRACKING,
    // AvailableSettings.ENHANCER_ENABLE_LAZY_INITIALIZATION,
    // AvailableSettings.ENHANCER_ENABLE_ASSOCIATION_MANAGEMENT

    // for the time being we want to revoke access to the temp ClassLoader if one
    // was passed
    metamodelBuilder.applyTempClassLoader(null);

    if (strategy != null && strategy != MultiTenancyStrategy.NONE) {
        ssrBuilder.addService(MultiTenantConnectionProvider.class, new HibernateMultiTenantConnectionProvider());
    }
    this.multiTenancyStrategy = strategy;

}