org.hibernate.jpa.AvailableSettings Java Examples

The following examples show how to use org.hibernate.jpa.AvailableSettings. 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: EntityManagerFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void configure(StandardServiceRegistry ssr, MergedSettings mergedSettings) {
	final StrategySelector strategySelector = ssr.getService( StrategySelector.class );

	// apply id generators
	final Object idGeneratorStrategyProviderSetting = configurationValues.remove( AvailableSettings.IDENTIFIER_GENERATOR_STRATEGY_PROVIDER );
	if ( idGeneratorStrategyProviderSetting != null ) {
		final IdentifierGeneratorStrategyProvider idGeneratorStrategyProvider =
				strategySelector.resolveStrategy( IdentifierGeneratorStrategyProvider.class, idGeneratorStrategyProviderSetting );
		final MutableIdentifierGeneratorFactory identifierGeneratorFactory = ssr.getService( MutableIdentifierGeneratorFactory.class );
		if ( identifierGeneratorFactory == null ) {
			throw persistenceException(
					"Application requested custom identifier generator strategies, " +
							"but the MutableIdentifierGeneratorFactory could not be found"
			);
		}
		for ( Map.Entry<String,Class<?>> entry : idGeneratorStrategyProvider.getStrategies().entrySet() ) {
			identifierGeneratorFactory.register( entry.getKey(), entry.getValue() );
		}
	}
}
 
Example #2
Source File: CascadeLockTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testCascadeLockOnManagedEntityWithAssociationsInitializedAndJpa() throws InterruptedException {
    LOGGER.info("Test lock cascade for managed entity");
    doInJPA(entityManager -> {
        Post post = entityManager.createQuery(
                "select p " +
                        "from Post p " +
                        "join fetch p.details " +
                        "where p.id = :id", Post.class)
                .setParameter("id", 1L)
                .getSingleResult();
        entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
            AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
        ));
    });
}
 
Example #3
Source File: CascadeLockElementCollectionTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testCascadeLockOnManagedEntityWithAssociationsInitializedAndJpa() throws InterruptedException {
    LOGGER.info("Test lock cascade for managed entity");
    doInJPA(entityManager -> {
        Post post = entityManager.createQuery(
                "select p " +
                        "from Post p " +
                        "join fetch p.details " +
                        "where p.id = :id", Post.class)
                .setParameter("id", 1L)
                .getSingleResult();
        entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
            AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
        ));
    });
}
 
Example #4
Source File: CascadeLockUnidirectionalOneToManyTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testCascadeLockOnManagedEntityWithAssociationsInitializedAndJpa() throws InterruptedException {
    LOGGER.info("Test lock cascade for managed entity");
    doInJPA(entityManager -> {
        Post post = entityManager.createQuery(
                "select p " +
                        "from Post p " +
                        "join fetch p.details " +
                        "where p.id = :id", Post.class)
                .setParameter("id", 1L)
                .getSingleResult();
        entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
            AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
        ));
    });
}
 
Example #5
Source File: EntityManagerFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void populate(
		MetadataBuilder metamodelBuilder,
		MergedSettings mergedSettings,
		StandardServiceRegistry ssr,
		List<AttributeConverterDefinition> attributeConverterDefinitions) {
	( (MetadataBuilderImplementor) metamodelBuilder ).getBootstrapContext().markAsJpaBootstrap();

	if ( persistenceUnit.getTempClassLoader() != null ) {
		metamodelBuilder.applyTempClassLoader( persistenceUnit.getTempClassLoader() );
	}

	metamodelBuilder.applyScanEnvironment( new StandardJpaScanEnvironmentImpl( persistenceUnit ) );
	metamodelBuilder.applyScanOptions(
			new StandardScanOptions(
					(String) configurationValues.get( org.hibernate.cfg.AvailableSettings.SCANNER_DISCOVERY ),
					persistenceUnit.isExcludeUnlistedClasses()
			)
	);

	if ( mergedSettings.cacheRegionDefinitions != null ) {
		mergedSettings.cacheRegionDefinitions.forEach( metamodelBuilder::applyCacheRegionDefinition );
	}

	final TypeContributorList typeContributorList = (TypeContributorList) configurationValues.remove(
			TYPE_CONTRIBUTORS
	);
	if ( typeContributorList != null ) {
		typeContributorList.getTypeContributors().forEach( metamodelBuilder::applyTypes );
	}

	if ( attributeConverterDefinitions != null ) {
		attributeConverterDefinitions.forEach( metamodelBuilder::applyAttributeConverter );
	}
}
 
Example #6
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void setDefaultProperties() {
	properties.putIfAbsent( AvailableSettings.FLUSH_MODE, getHibernateFlushMode().name() );
	properties.putIfAbsent( JPA_LOCK_SCOPE, PessimisticLockScope.EXTENDED.name() );
	properties.putIfAbsent( JPA_LOCK_TIMEOUT, LockOptions.WAIT_FOREVER );
	properties.putIfAbsent( JPA_SHARED_CACHE_RETRIEVE_MODE, CacheModeHelper.DEFAULT_RETRIEVE_MODE );
	properties.putIfAbsent( JPA_SHARED_CACHE_STORE_MODE, CacheModeHelper.DEFAULT_STORE_MODE );
}
 
Example #7
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void applyProperties() {
	applyEntityManagerSpecificProperties();
	setHibernateFlushMode( ConfigurationHelper.getFlushMode( properties.get( AvailableSettings.FLUSH_MODE ), FlushMode.AUTO ) );
	setLockOptions( this.properties, this.lockOptions );
	getSession().setCacheMode(
			CacheModeHelper.interpretCacheMode(
					currentCacheStoreMode(),
					currentCacheRetrieveMode()
			)
	);
}
 
Example #8
Source File: CascadeLockTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Test
public void testCascadeLockOnManagedEntityWithJPA() throws InterruptedException {
    LOGGER.info("Test lock cascade for managed entity");
    doInJPA(entityManager -> {
        Post post = entityManager.find(Post.class, 1L);
        entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
            AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
        ));
    });
}
 
Example #9
Source File: CascadeLockElementCollectionTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Test
public void testCascadeLockOnManagedEntityWithJPA() throws InterruptedException {
    LOGGER.info("Test lock cascade for managed entity");
    doInJPA(entityManager -> {
        Post post = entityManager.find(Post.class, 1L);
        entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
            AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
        ));
    });
}
 
Example #10
Source File: CascadeLockElementCollectionTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Test
public void testCascadeLockOnManagedEntityWithAssociationsUninitializedAndJpa() throws InterruptedException {
    LOGGER.info("Test lock cascade for managed entity");
    doInJPA(entityManager -> {
        Post post = entityManager.find(Post.class, 1L);
        entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
            AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
        ));
    });
}
 
Example #11
Source File: CascadeLockUnidirectionalOneToManyTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Test
public void testCascadeLockOnManagedEntityWithJPA() throws InterruptedException {
    LOGGER.info("Test lock cascade for managed entity");
    doInJPA(entityManager -> {
        Post post = entityManager.find(Post.class, 1L);
        entityManager.lock(post, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(
            AvailableSettings.LOCK_SCOPE, PessimisticLockScope.EXTENDED
        ));
    });
}
 
Example #12
Source File: FastBootEntityManagerFactoryBuilder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
protected void populate(SessionFactoryOptionsBuilder options, StandardServiceRegistry ssr, MultiTenancyStrategy strategy) {

        // will use user override value or default to false if not supplied to follow
        // JPA spec.
        final boolean jtaTransactionAccessEnabled = runtimeSettings.getBoolean(
                AvailableSettings.ALLOW_JTA_TRANSACTION_ACCESS);
        if (!jtaTransactionAccessEnabled) {
            options.disableJtaTransactionAccess();
        }

        final boolean allowRefreshDetachedEntity = runtimeSettings.getBoolean(
                org.hibernate.cfg.AvailableSettings.ALLOW_REFRESH_DETACHED_ENTITY);
        if (!allowRefreshDetachedEntity) {
            options.disableRefreshDetachedEntity();
        }

        // Locate and apply any requested SessionFactoryObserver
        final Object sessionFactoryObserverSetting = runtimeSettings.get(AvailableSettings.SESSION_FACTORY_OBSERVER);
        if (sessionFactoryObserverSetting != null) {

            final StrategySelector strategySelector = ssr.getService(StrategySelector.class);
            final SessionFactoryObserver suppliedSessionFactoryObserver = strategySelector
                    .resolveStrategy(SessionFactoryObserver.class, sessionFactoryObserverSetting);
            options.addSessionFactoryObservers(suppliedSessionFactoryObserver);
        }

        options.addSessionFactoryObservers(new ServiceRegistryCloser());

        options.applyEntityNotFoundDelegate(new JpaEntityNotFoundDelegate());

        if (this.validatorFactory != null) {
            options.applyValidatorFactory(validatorFactory);
        }
        if (this.cdiBeanManager != null) {
            options.applyBeanManager(cdiBeanManager);
        }

        //Small memory optimisations: ensure the class transformation caches of the bytecode enhancer
        //are cleared both on start and on close of the SessionFactory.
        //(On start is useful especially in Quarkus as we won't do any more enhancement after this point)
        BytecodeProvider bytecodeProvider = ssr.getService(BytecodeProvider.class);
        options.addSessionFactoryObservers(new SessionFactoryObserverForBytecodeEnhancer(bytecodeProvider));

        if (strategy != null && strategy != MultiTenancyStrategy.NONE) {
            options.applyMultiTenancyStrategy(strategy);
            options.applyCurrentTenantIdentifierResolver(new HibernateCurrentTenantIdentifierResolver());
        }

    }
 
Example #13
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 #14
Source File: EntityManagerFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
	protected List<AttributeConverterDefinition> populate(
			MetadataSources metadataSources,
			MergedSettings mergedSettings,
			StandardServiceRegistry ssr) {
//		final ClassLoaderService classLoaderService = ssr.getService( ClassLoaderService.class );
//
//		// todo : make sure MetadataSources/Metadata are capable of handling duplicate sources
//
//		// explicit persistence unit mapping files listings
//		if ( persistenceUnit.getMappingFileNames() != null ) {
//			for ( String name : persistenceUnit.getMappingFileNames() ) {
//				metadataSources.addResource( name );
//			}
//		}
//
//		// explicit persistence unit managed class listings
//		//		IMPL NOTE : managed-classes can contain class or package names!!!
//		if ( persistenceUnit.getManagedClassNames() != null ) {
//			for ( String managedClassName : persistenceUnit.getManagedClassNames() ) {
//				// try it as a class name first...
//				final String classFileName = managedClassName.replace( '.', '/' ) + ".class";
//				final URL classFileUrl = classLoaderService.locateResource( classFileName );
//				if ( classFileUrl != null ) {
//					// it is a class
//					metadataSources.addAnnotatedClassName( managedClassName );
//					continue;
//				}
//
//				// otherwise, try it as a package name
//				final String packageInfoFileName = managedClassName.replace( '.', '/' ) + "/package-info.class";
//				final URL packageInfoFileUrl = classLoaderService.locateResource( packageInfoFileName );
//				if ( packageInfoFileUrl != null ) {
//					// it is a package
//					metadataSources.addPackage( managedClassName );
//					continue;
//				}
//
//				LOG.debugf(
//						"Unable to resolve class [%s] named in persistence unit [%s]",
//						managedClassName,
//						persistenceUnit.getName()
//				);
//			}
//		}

		List<AttributeConverterDefinition> attributeConverterDefinitions = null;

		// add any explicit Class references passed in
		final List<Class> loadedAnnotatedClasses = (List<Class>) configurationValues.remove( AvailableSettings.LOADED_CLASSES );
		if ( loadedAnnotatedClasses != null ) {
			for ( Class cls : loadedAnnotatedClasses ) {
				if ( AttributeConverter.class.isAssignableFrom( cls ) ) {
					if ( attributeConverterDefinitions == null ) {
						attributeConverterDefinitions = new ArrayList<>();
					}
					attributeConverterDefinitions.add( AttributeConverterDefinition.from( (Class<? extends AttributeConverter>) cls ) );
				}
				else {
					metadataSources.addAnnotatedClass( cls );
				}
			}
		}

		// add any explicit hbm.xml references passed in
		final String explicitHbmXmls = (String) configurationValues.remove( AvailableSettings.HBXML_FILES );
		if ( explicitHbmXmls != null ) {
			for ( String hbmXml : StringHelper.split( ", ", explicitHbmXmls ) ) {
				metadataSources.addResource( hbmXml );
			}
		}

		// add any explicit orm.xml references passed in
		final List<String> explicitOrmXmlList = (List<String>) configurationValues.remove( AvailableSettings.XML_FILE_NAMES );
		if ( explicitOrmXmlList != null ) {
			explicitOrmXmlList.forEach( metadataSources::addResource );
		}

		return attributeConverterDefinitions;
	}
 
Example #15
Source File: EntityManagerFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected void populate(SessionFactoryBuilder sfBuilder, StandardServiceRegistry ssr) {

		final StrategySelector strategySelector = ssr.getService( StrategySelector.class );

//		// Locate and apply the requested SessionFactory-level interceptor (if one)
//		final Object sessionFactoryInterceptorSetting = configurationValues.remove( org.hibernate.cfg.AvailableSettings.INTERCEPTOR );
//		if ( sessionFactoryInterceptorSetting != null ) {
//			final Interceptor sessionFactoryInterceptor =
//					strategySelector.resolveStrategy( Interceptor.class, sessionFactoryInterceptorSetting );
//			sfBuilder.applyInterceptor( sessionFactoryInterceptor );
//		}

		// will use user override value or default to false if not supplied to follow JPA spec.
		final boolean jtaTransactionAccessEnabled = readBooleanConfigurationValue( AvailableSettings.ALLOW_JTA_TRANSACTION_ACCESS );
		if ( !jtaTransactionAccessEnabled ) {
			( ( SessionFactoryBuilderImplementor ) sfBuilder ).disableJtaTransactionAccess();
		}

		final boolean allowRefreshDetachedEntity = readBooleanConfigurationValue( org.hibernate.cfg.AvailableSettings.ALLOW_REFRESH_DETACHED_ENTITY );
		if ( !allowRefreshDetachedEntity ) {
			( (SessionFactoryBuilderImplementor) sfBuilder ).disableRefreshDetachedEntity();
		}

		// Locate and apply any requested SessionFactoryObserver
		final Object sessionFactoryObserverSetting = configurationValues.remove( AvailableSettings.SESSION_FACTORY_OBSERVER );
		if ( sessionFactoryObserverSetting != null ) {
			final SessionFactoryObserver suppliedSessionFactoryObserver =
					strategySelector.resolveStrategy( SessionFactoryObserver.class, sessionFactoryObserverSetting );
			sfBuilder.addSessionFactoryObservers( suppliedSessionFactoryObserver );
		}

		sfBuilder.addSessionFactoryObservers( ServiceRegistryCloser.INSTANCE );

		sfBuilder.applyEntityNotFoundDelegate( JpaEntityNotFoundDelegate.INSTANCE );

		if ( this.validatorFactory != null ) {
			sfBuilder.applyValidatorFactory( validatorFactory );
		}
		if ( this.cdiBeanManager != null ) {
			sfBuilder.applyBeanManager( cdiBeanManager );
		}
	}