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

The following examples show how to use org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider. 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: HibernateConfig.java    From spring-boot-multitenant with 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 #2
Source File: HibernateConfig.java    From cloud-s4-sdk-examples with 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 #3
Source File: AbstractSharedSessionContract.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 File: SessionFactoryImpl.java    From lams with 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 #5
Source File: MultiTenancyJpaConfiguration.java    From multitenancy with 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 #6
Source File: ContextualJdbcConnectionAccess.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ContextualJdbcConnectionAccess(
		String tenantIdentifier,
		SessionEventListener listener,
		MultiTenantConnectionProvider connectionProvider) {
	this.tenantIdentifier = tenantIdentifier;
	this.listener = listener;
	this.connectionProvider = connectionProvider;
}
 
Example #7
Source File: JdbcEnvironmentInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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
Source File: JdbcEnvironmentInitiator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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 #9
Source File: MultiTenantConnectionProviderInitiator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@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 #10
Source File: JdbcEnvironmentInitiator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public MultiTenantConnectionProvider getConnectionProvider() {
	return connectionProvider;
}
 
Example #11
Source File: JdbcEnvironmentInitiator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public MultiTenantConnectionProviderJdbcConnectionAccess(MultiTenantConnectionProvider connectionProvider) {
	this.connectionProvider = connectionProvider;
}
 
Example #12
Source File: MultiTenantConnectionProviderInitiator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Class<MultiTenantConnectionProvider> getServiceInitiated() {
	return MultiTenantConnectionProvider.class;
}
 
Example #13
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 #14
Source File: LocalSessionFactoryBean.java    From spring-analysis-note with 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 File: LocalSessionFactoryBuilder.java    From lams with 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 AvailableSettings#MULTI_TENANT_CONNECTION_PROVIDER
 */
public LocalSessionFactoryBuilder setMultiTenantConnectionProvider(MultiTenantConnectionProvider multiTenantConnectionProvider) {
	getProperties().put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
	return this;
}
 
Example #16
Source File: LocalSessionFactoryBean.java    From lams with 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 #17
Source File: MultiTenancyJpaConfiguration.java    From multitenancy with 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 #18
Source File: LocalSessionFactoryBuilder.java    From java-technology-stack with 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 #19
Source File: LocalSessionFactoryBean.java    From java-technology-stack with 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 #20
Source File: LocalSessionFactoryBuilder.java    From spring-analysis-note with 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;
}