Java Code Examples for org.hibernate.MultiTenancyStrategy#NONE

The following examples show how to use org.hibernate.MultiTenancyStrategy#NONE . 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: HibernateOrmProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
void registerBeans(BuildProducer<AdditionalBeanBuildItem> additionalBeans, Capabilities capabilities,
        CombinedIndexBuildItem combinedIndex,
        List<PersistenceUnitDescriptorBuildItem> descriptors,
        JpaEntitiesBuildItem jpaEntities, List<NonJpaModelBuildItem> nonJpaModels) {
    if (!hasEntities(jpaEntities, nonJpaModels)) {
        return;
    }

    List<Class<?>> unremovableClasses = new ArrayList<>();
    unremovableClasses.add(JPAConfig.class);
    if (capabilities.isPresent(Capability.TRANSACTIONS)) {
        unremovableClasses.add(TransactionManager.class);
        unremovableClasses.add(TransactionEntityManagers.class);
    }
    unremovableClasses.add(RequestScopedEntityManagerHolder.class);
    if (getMultiTenancyStrategy() != MultiTenancyStrategy.NONE) {
        unremovableClasses.add(DataSourceTenantConnectionResolver.class);
    }

    additionalBeans.produce(AdditionalBeanBuildItem.builder().setUnremovable()
            .addBeanClasses(unremovableClasses.toArray(new Class<?>[unremovableClasses.size()]))
            .build());

    if (descriptors.size() == 1) {
        // There is only one persistence unit - register CDI beans for EM and EMF if no
        // producers are defined
        if (isUserDefinedProducerMissing(combinedIndex.getIndex(), PERSISTENCE_UNIT)) {
            additionalBeans.produce(new AdditionalBeanBuildItem(DefaultEntityManagerFactoryProducer.class));
        }
        if (isUserDefinedProducerMissing(combinedIndex.getIndex(), PERSISTENCE_CONTEXT)) {
            additionalBeans.produce(new AdditionalBeanBuildItem(DefaultEntityManagerProducer.class));
        }
    }
}
 
Example 2
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 3
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;

}
 
Example 4
Source File: AbstractSharedSessionContract.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public AbstractSharedSessionContract(SessionFactoryImpl factory, SessionCreationOptions options) {
	this.factory = factory;
	this.cacheTransactionSync = factory.getCache().getRegionFactory().createTransactionContext( this );

	this.flushMode = options.getInitialSessionFlushMode();

	this.tenantIdentifier = options.getTenantIdentifier();
	if ( MultiTenancyStrategy.NONE == factory.getSettings().getMultiTenancyStrategy() ) {
		if ( tenantIdentifier != null ) {
			throw new HibernateException( "SessionFactory was not configured for multi-tenancy" );
		}
	}
	else {
		if ( tenantIdentifier == null ) {
			throw new HibernateException( "SessionFactory configured for multi-tenancy, but no tenant identifier specified" );
		}
	}

	this.interceptor = interpret( options.getInterceptor() );
	this.jdbcTimeZone = options.getJdbcTimeZone();

	final StatementInspector statementInspector = interpret( options.getStatementInspector() );
	this.jdbcSessionContext = new JdbcSessionContextImpl( this, statementInspector );

	this.entityNameResolver = new CoordinatingEntityNameResolver( factory, interceptor );

	if ( options instanceof SharedSessionCreationOptions && ( (SharedSessionCreationOptions) options ).isTransactionCoordinatorShared() ) {
		if ( options.getConnection() != null ) {
			throw new SessionException( "Cannot simultaneously share transaction context and specify connection" );
		}

		this.isTransactionCoordinatorShared = true;

		final SharedSessionCreationOptions sharedOptions = (SharedSessionCreationOptions) options;
		this.transactionCoordinator = sharedOptions.getTransactionCoordinator();
		this.jdbcCoordinator = sharedOptions.getJdbcCoordinator();

		// todo : "wrap" the transaction to no-op cmmit/rollback attempts?
		this.currentHibernateTransaction = sharedOptions.getTransaction();

		if ( sharedOptions.shouldAutoJoinTransactions() ) {
			log.debug(
					"Session creation specified 'autoJoinTransactions', which is invalid in conjunction " +
							"with sharing JDBC connection between sessions; ignoring"
			);
			autoJoinTransactions = false;
		}
		if ( sharedOptions.getPhysicalConnectionHandlingMode() != this.jdbcCoordinator.getLogicalConnection().getConnectionHandlingMode() ) {
			log.debug(
					"Session creation specified 'PhysicalConnectionHandlingMode which is invalid in conjunction " +
							"with sharing JDBC connection between sessions; ignoring"
			);
		}

		addSharedSessionTransactionObserver( transactionCoordinator );
	}
	else {
		this.isTransactionCoordinatorShared = false;
		this.autoJoinTransactions = options.shouldAutoJoinTransactions();

		this.jdbcCoordinator = new JdbcCoordinatorImpl( options.getConnection(), this );
		this.transactionCoordinator = factory.getServiceRegistry()
				.getService( TransactionCoordinatorBuilder.class )
				.buildTransactionCoordinator( jdbcCoordinator, this );
	}
	exceptionConverter = new ExceptionConverterImpl( this );
}