Java Code Examples for org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider

The following examples show how to use org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider. These examples are extracted from open source projects. 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 Project: multitenancy   Source File: MultiTenancyJpaConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * org.springframework.beans.factory.FactoryBean that creates a JPA
 * {@link javax.persistence.EntityManagerFactory} according to JPA's standard
 * container bootstrap contract. This is the most powerful way to set up a
 * shared JPA EntityManagerFactory in a Spring application context; the
 * EntityManagerFactory can then be passed to JPA-based DAOs via dependency
 * injection. Note that switching to a JNDI lookup or to a
 * {@link org.springframework.orm.jpa.LocalEntityManagerFactoryBean} definition
 * is just a matter of configuration!
 * 
 * @param multiTenantConnectionProvider
 * @param currentTenantIdentifierResolver
 * @return
 */
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
        MultiTenantConnectionProvider multiTenantConnectionProvider,
        CurrentTenantIdentifierResolver currentTenantIdentifierResolver) {

    Map<String, Object> hibernateProps = new LinkedHashMap<>();
    hibernateProps.putAll(this.jpaProperties.getProperties());
    hibernateProps.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
    hibernateProps.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
    hibernateProps.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver);

    // No dataSource is set to resulting entityManagerFactoryBean
    LocalContainerEntityManagerFactoryBean result = new LocalContainerEntityManagerFactoryBean();
    result.setPackagesToScan(new String[] { Employee.class.getPackage().getName() });
    result.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    result.setJpaPropertyMap(hibernateProps);

    return result;
}
 
Example 2
Source Project: lams   Source File: SessionFactoryImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
private JdbcConnectionAccess buildLocalConnectionAccess() {
	return new JdbcConnectionAccess() {
		@Override
		public Connection obtainConnection() throws SQLException {
			return !settings.getMultiTenancyStrategy().requiresMultiTenantConnectionProvider()
					? serviceRegistry.getService( ConnectionProvider.class ).getConnection()
					: serviceRegistry.getService( MultiTenantConnectionProvider.class ).getAnyConnection();
		}

		@Override
		public void releaseConnection(Connection connection) throws SQLException {
			if ( !settings.getMultiTenancyStrategy().requiresMultiTenantConnectionProvider() ) {
				serviceRegistry.getService( ConnectionProvider.class ).closeConnection( connection );
			}
			else {
				serviceRegistry.getService( MultiTenantConnectionProvider.class ).releaseAnyConnection( connection );
			}
		}

		@Override
		public boolean supportsAggressiveRelease() {
			return false;
		}
	};
}
 
Example 3
@Override
public JdbcConnectionAccess getJdbcConnectionAccess() {
	// See class-level JavaDocs for a discussion of the concurrent-access safety of this method
	if ( jdbcConnectionAccess == null ) {
		if ( !factory.getSettings().getMultiTenancyStrategy().requiresMultiTenantConnectionProvider() ) {
			jdbcConnectionAccess = new NonContextualJdbcConnectionAccess(
					getEventListenerManager(),
					factory.getServiceRegistry().getService( ConnectionProvider.class )
			);
		}
		else {
			jdbcConnectionAccess = new ContextualJdbcConnectionAccess(
					getTenantIdentifier(),
					getEventListenerManager(),
					factory.getServiceRegistry().getService( MultiTenantConnectionProvider.class )
			);
		}
	}
	return jdbcConnectionAccess;
}
 
Example 4
Source Project: cloud-s4-sdk-examples   Source File: HibernateConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, MultiTenantConnectionProvider multiTenantConnectionProvider,
                                                                   CurrentTenantIdentifierResolver tenantIdentifierResolver) {
    final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource);
    em.setPackagesToScan("com.mycompany.models");

    em.setJpaVendorAdapter(this.jpaVendorAdapter());

    final Map<String, Object> jpaProperties = new HashMap<>();
    jpaProperties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
    jpaProperties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
    jpaProperties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantIdentifierResolver);
    jpaProperties.put(Environment.FORMAT_SQL, true);

    em.setJpaPropertyMap(jpaProperties);
    return em;
}
 
Example 5
Source Project: spring-boot-multitenant   Source File: HibernateConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
    MultiTenantConnectionProvider multiTenantConnectionProviderImpl,
    CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl) {
  Map<String, Object> properties = new HashMap<>();
  properties.putAll(jpaProperties.getHibernateProperties(dataSource));
  properties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
  properties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl);
  properties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolverImpl);

  LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
  em.setDataSource(dataSource);
  em.setPackagesToScan("com.srai");
  em.setJpaVendorAdapter(jpaVendorAdapter());
  em.setJpaPropertyMap(properties);
  return em;
}
 
Example 6
private JdbcConnectionAccess buildJdbcConnectionAccess(Map configValues, ServiceRegistryImplementor registry) {
	final MultiTenancyStrategy multiTenancyStrategy = MultiTenancyStrategy.determineMultiTenancyStrategy(
			configValues
	);
	if ( !multiTenancyStrategy.requiresMultiTenantConnectionProvider() ) {
		ConnectionProvider connectionProvider = registry.getService( ConnectionProvider.class );
		return new ConnectionProviderJdbcConnectionAccess( connectionProvider );
	}
	else {
		final MultiTenantConnectionProvider multiTenantConnectionProvider = registry.getService( MultiTenantConnectionProvider.class );
		return new MultiTenantConnectionProviderJdbcConnectionAccess( multiTenantConnectionProvider );
	}
}
 
Example 7
public static JdbcConnectionAccess buildBootstrapJdbcConnectionAccess(
		MultiTenancyStrategy multiTenancyStrategy,
		ServiceRegistryImplementor registry) {
	if ( !multiTenancyStrategy.requiresMultiTenantConnectionProvider() ) {
		ConnectionProvider connectionProvider = registry.getService( ConnectionProvider.class );
		return new ConnectionProviderJdbcConnectionAccess( connectionProvider );
	}
	else {
		final MultiTenantConnectionProvider multiTenantConnectionProvider = registry.getService( MultiTenantConnectionProvider.class );
		return new MultiTenantConnectionProviderJdbcConnectionAccess( multiTenantConnectionProvider );
	}
}
 
Example 8
public ContextualJdbcConnectionAccess(
		String tenantIdentifier,
		SessionEventListener listener,
		MultiTenantConnectionProvider connectionProvider) {
	this.tenantIdentifier = tenantIdentifier;
	this.listener = listener;
	this.connectionProvider = connectionProvider;
}
 
Example 9
Source Project: quarkus   Source File: FastBootMetadataBuilder.java    License: 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 10
@Override
public Class<MultiTenantConnectionProvider> getServiceInitiated() {
	return MultiTenantConnectionProvider.class;
}
 
Example 11
@Override
@SuppressWarnings( {"unchecked"})
public MultiTenantConnectionProvider initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
	final MultiTenancyStrategy strategy = MultiTenancyStrategy.determineMultiTenancyStrategy(  configurationValues );
	if ( !strategy.requiresMultiTenantConnectionProvider() ) {
		// nothing to do, but given the separate hierarchies have to handle this here.
		return null;
	}

	final Object configValue = configurationValues.get( AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER );
	if ( configValue == null ) {
		// if they also specified the data source *name*, then lets assume they want
		// DataSourceBasedMultiTenantConnectionProviderImpl
		final Object dataSourceConfigValue = configurationValues.get( AvailableSettings.DATASOURCE );
		if ( dataSourceConfigValue != null && String.class.isInstance( dataSourceConfigValue ) ) {
			return new DataSourceBasedMultiTenantConnectionProviderImpl();
		}

		return null;
	}

	if ( MultiTenantConnectionProvider.class.isInstance( configValue ) ) {
		return (MultiTenantConnectionProvider) configValue;
	}
	else {
		final Class<MultiTenantConnectionProvider> implClass;
		if ( Class.class.isInstance( configValue ) ) {
			implClass = (Class) configValue;
		}
		else {
			final String className = configValue.toString();
			final ClassLoaderService classLoaderService = registry.getService( ClassLoaderService.class );
			try {
				implClass = classLoaderService.classForName( className );
			}
			catch (ClassLoadingException cle) {
				log.warn( "Unable to locate specified class [" + className + "]", cle );
				throw new ServiceException( "Unable to locate specified multi-tenant connection provider [" + className + "]" );
			}
		}

		try {
			return implClass.newInstance();
		}
		catch (Exception e) {
			log.warn( "Unable to instantiate specified class [" + implClass.getName() + "]", e );
			throw new ServiceException( "Unable to instantiate specified multi-tenant connection provider [" + implClass.getName() + "]" );
		}
	}
}
 
Example 12
public MultiTenantConnectionProviderJdbcConnectionAccess(MultiTenantConnectionProvider connectionProvider) {
	this.connectionProvider = connectionProvider;
}
 
Example 13
public MultiTenantConnectionProvider getConnectionProvider() {
	return connectionProvider;
}
 
Example 14
Source Project: spring-analysis-note   Source File: LocalSessionFactoryBean.java    License: MIT License 2 votes vote down vote up
/**
 * Set a {@link MultiTenantConnectionProvider} to be passed on to the SessionFactory.
 * @since 4.3
 * @see LocalSessionFactoryBuilder#setMultiTenantConnectionProvider
 */
public void setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider) {
	this.multiTenantConnectionProvider = multiTenantConnectionProvider;
}
 
Example 15
Source Project: spring-analysis-note   Source File: LocalSessionFactoryBuilder.java    License: MIT License 2 votes vote down vote up
/**
 * Set a {@link MultiTenantConnectionProvider} to be passed on to the SessionFactory.
 * @since 4.3
 * @see AvailableSettings#MULTI_TENANT_CONNECTION_PROVIDER
 */
public LocalSessionFactoryBuilder setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider) {
	getProperties().put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
	return this;
}
 
Example 16
Source Project: java-technology-stack   Source File: LocalSessionFactoryBean.java    License: MIT License 2 votes vote down vote up
/**
 * Set a {@link MultiTenantConnectionProvider} to be passed on to the SessionFactory.
 * @since 4.3
 * @see LocalSessionFactoryBuilder#setMultiTenantConnectionProvider
 */
public void setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider) {
	this.multiTenantConnectionProvider = multiTenantConnectionProvider;
}
 
Example 17
Source Project: java-technology-stack   Source File: LocalSessionFactoryBuilder.java    License: MIT License 2 votes vote down vote up
/**
 * Set a {@link MultiTenantConnectionProvider} to be passed on to the SessionFactory.
 * @since 4.3
 * @see AvailableSettings#MULTI_TENANT_CONNECTION_PROVIDER
 */
public LocalSessionFactoryBuilder setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider) {
	getProperties().put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
	return this;
}
 
Example 18
Source Project: multitenancy   Source File: MultiTenancyJpaConfiguration.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Autowires the data sources so that they can be used by the Spring JPA to
 * access the database
 * 
 * @return
 */
@Bean
public MultiTenantConnectionProvider multiTenantConnectionProvider() {
    // Autowires dataSourcesMtApp
    return new DataSourceBasedMultiTenantConnectionProviderImpl();
}
 
Example 19
Source Project: lams   Source File: LocalSessionFactoryBean.java    License: GNU General Public License v2.0 2 votes vote down vote up
/**
 * Set a {@link MultiTenantConnectionProvider} to be passed on to the SessionFactory.
 * @since 4.3
 * @see LocalSessionFactoryBuilder#setMultiTenantConnectionProvider
 */
public void setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider) {
	this.multiTenantConnectionProvider = multiTenantConnectionProvider;
}
 
Example 20
/**
 * Set a {@link MultiTenantConnectionProvider} to be passed on to the SessionFactory.
 * @since 4.3
 * @see AvailableSettings#MULTI_TENANT_CONNECTION_PROVIDER
 */
public LocalSessionFactoryBuilder setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider) {
	getProperties().put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
	return this;
}