org.hibernate.MultiTenancyStrategy Java Examples

The following examples show how to use org.hibernate.MultiTenancyStrategy. 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 7 votes vote down vote up
@BuildStep
@Record(STATIC_INIT)
public void build(HibernateOrmRecorder recorder,
        Capabilities capabilities, BuildProducer<BeanContainerListenerBuildItem> buildProducer,
        List<PersistenceUnitDescriptorBuildItem> descriptors,
        JpaEntitiesBuildItem jpaEntities, List<NonJpaModelBuildItem> nonJpaModels) throws Exception {
    if (!hasEntities(jpaEntities, nonJpaModels)) {
        return;
    }
    MultiTenancyStrategy strategy = MultiTenancyStrategy
            .valueOf(hibernateConfig.multitenant.orElse(MultiTenancyStrategy.NONE.name()));
    buildProducer.produce(new BeanContainerListenerBuildItem(
            recorder.initializeJpa(capabilities.isPresent(Capability.TRANSACTIONS), strategy,
                    hibernateConfig.multitenantSchemaDatasource.orElse(null))));

    // Bootstrap all persistence units
    for (PersistenceUnitDescriptorBuildItem persistenceUnitDescriptor : descriptors) {
        buildProducer.produce(new BeanContainerListenerBuildItem(
                recorder.registerPersistenceUnit(persistenceUnitDescriptor.getDescriptor().getName())));
    }
    buildProducer.produce(new BeanContainerListenerBuildItem(recorder.initDefaultPersistenceUnit()));
}
 
Example #2
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 #3
Source File: DataSourceTenantConnectionResolver.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public ConnectionProvider resolve(String tenantId) {

    LOG.debugv("resolve({0})", tenantId);

    final MultiTenancyStrategy strategy = jpaConfig.getMultiTenancyStrategy();
    LOG.debugv("multitenancy strategy: {0}", strategy);
    AgroalDataSource dataSource = tenantDataSource(jpaConfig, tenantId, strategy);
    if (dataSource == null) {
        throw new IllegalStateException("No instance of datasource found for tenant: " + tenantId);
    }
    if (strategy == MultiTenancyStrategy.SCHEMA) {
        return new TenantConnectionProvider(tenantId, dataSource);
    }
    return new QuarkusConnectionProvider(dataSource);
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
Source File: TenancySampleApplication.java    From tenancy-sample with Apache License 2.0 5 votes vote down vote up
public
@Bean
EntityManagerFactory customEntityManagerFactory(DataSource dataSource) {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(false); // turn off with Discriminator strategy so far!
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan(TenancySampleApplication.class.getPackage().getName());
    factory.setDataSource(dataSource);
    factory.getJpaPropertyMap().put(Environment.DIALECT, PostgreSQL9Dialect.class.getName());
    factory.getJpaPropertyMap().put(Environment.MULTI_TENANT, MultiTenancyStrategy.DISCRIMINATOR);
    factory.getJpaPropertyMap().put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, new TenantHolder());
    factory.afterPropertiesSet();
    return factory.getObject();
}
 
Example #9
Source File: CatalogMultitenancyTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Override
protected void additionalProperties(Properties properties) {
    properties.setProperty(AvailableSettings.HBM2DDL_AUTO, "none");
    properties.setProperty(AvailableSettings.SHOW_SQL, "true");
    properties.setProperty(AvailableSettings.MULTI_TENANT, MultiTenancyStrategy.DATABASE.name());
    properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, MultiTenantConnectionProvider.INSTANCE);
    properties.setProperty(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, TenantContext.TenantIdentifierResolver.class.getName());
}
 
Example #10
Source File: SchemaMultitenancyTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Override
protected void additionalProperties(Properties properties) {
    properties.setProperty(AvailableSettings.HBM2DDL_AUTO, "none");
    properties.setProperty(AvailableSettings.MULTI_TENANT, MultiTenancyStrategy.SCHEMA.name());
    properties.setProperty(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, TenantContext.TenantIdentifierResolver.class.getName());
    properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, MultiTenantConnectionProvider.INSTANCE);
}
 
Example #11
Source File: MultiTenancyJpaConfiguration.java    From multitenancy with GNU General Public License v2.0 5 votes vote down vote up
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
	Map<String, Object> hibernateProps = new LinkedHashMap<>();
	hibernateProps.putAll(jpaProperties.getHibernateProperties(dataSource));

	hibernateProps.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
	hibernateProps.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
	hibernateProps.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver);
	hibernateProps.put(Environment.DIALECT, "org.hibernate.dialect.MySQLDialect");

	return builder.dataSource(dataSource).packages(Employee.class.getPackage().getName()).properties(hibernateProps).jta(false).build();
}
 
Example #12
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 #13
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 #14
Source File: QuarkusReactiveConnectionPoolInitiator.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public ReactiveConnectionPool initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
    //First, check that this setup won't need to deal with multi-tenancy at the connection pool level:
    final MultiTenancyStrategy strategy = MultiTenancyStrategy.determineMultiTenancyStrategy(configurationValues);
    if (strategy == MultiTenancyStrategy.DATABASE || strategy == MultiTenancyStrategy.SCHEMA) {
        // nothing to do, but given the separate hierarchies have to handle this here.
        return null;
    }

    return new QuarkusReactiveConnectionPool(pool);
}
 
Example #15
Source File: FastBootEntityManagerFactoryBuilder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public FastBootEntityManagerFactoryBuilder(
        PrevalidatedQuarkusMetadata metadata, String persistenceUnitName,
        StandardServiceRegistry standardServiceRegistry, RuntimeSettings runtimeSettings, Object validatorFactory,
        Object cdiBeanManager, MultiTenancyStrategy strategy) {
    this.metadata = metadata;
    this.persistenceUnitName = persistenceUnitName;
    this.standardServiceRegistry = standardServiceRegistry;
    this.runtimeSettings = runtimeSettings;
    this.validatorFactory = validatorFactory;
    this.cdiBeanManager = cdiBeanManager;
    this.multiTenancyStrategy = strategy;
}
 
Example #16
Source File: HibernateOrmProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private MultiTenancyStrategy getMultiTenancyStrategy() {
    final MultiTenancyStrategy multiTenancyStrategy = MultiTenancyStrategy
            .valueOf(hibernateConfig.multitenant.orElse(MultiTenancyStrategy.NONE.name()));
    if (multiTenancyStrategy == MultiTenancyStrategy.DISCRIMINATOR) {
        // See https://hibernate.atlassian.net/browse/HHH-6054
        throw new ConfigurationError("The Hibernate ORM multi tenancy strategy "
                + MultiTenancyStrategy.DISCRIMINATOR + " is currently not supported");
    }
    return multiTenancyStrategy;
}
 
Example #17
Source File: RecordedState.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public RecordedState(Dialect dialect, PrevalidatedQuarkusMetadata metadata,
        BuildTimeSettings settings, Collection<Integrator> integrators,
        Collection<ProvidedService> providedServices, IntegrationSettings integrationSettings,
        ProxyDefinitions classDefinitions, MultiTenancyStrategy strategy) {
    this.dialect = dialect;
    this.metadata = metadata;
    this.settings = settings;
    this.integrators = integrators;
    this.providedServices = providedServices;
    this.integrationSettings = integrationSettings;
    this.proxyClassDefinitions = classDefinitions;
    this.multiTenancyStrategy = strategy;
}
 
Example #18
Source File: HibernateOrmRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the JPA configuration to be used at runtime.
 * 
 * @param jtaEnabled Should JTA be enabled?
 * @param strategy Multitenancy strategy to use.
 * @param multiTenancySchemaDataSource Data source to use in case of {@link MultiTenancyStrategy#SCHEMA} approach or
 *        {@link null} in case the default data source.
 * 
 * @return
 */
public BeanContainerListener initializeJpa(boolean jtaEnabled, MultiTenancyStrategy strategy,
        String multiTenancySchemaDataSource) {
    return new BeanContainerListener() {
        @Override
        public void created(BeanContainer beanContainer) {
            JPAConfig instance = beanContainer.instance(JPAConfig.class);
            instance.setJtaEnabled(jtaEnabled);
            instance.setMultiTenancyStrategy(strategy);
            instance.setMultiTenancySchemaDataSource(multiTenancySchemaDataSource);
        }
    };
}
 
Example #19
Source File: JPAConfig.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public JPAConfig() {
    this.jtaEnabled = new AtomicBoolean();
    this.multiTenancyStrategy = new AtomicReference<MultiTenancyStrategy>();
    this.multiTenancySchemaDataSource = new AtomicReference<String>();
    this.persistenceUnits = new ConcurrentHashMap<>();
    this.defaultPersistenceUnitName = new AtomicReference<String>();
}
 
Example #20
Source File: HibernateOrmRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public BeanContainerListener initMetadata(List<ParsedPersistenceXmlDescriptor> parsedPersistenceXmlDescriptors,
        Scanner scanner, Collection<Class<? extends Integrator>> additionalIntegrators,
        PreGeneratedProxies proxyDefinitions, MultiTenancyStrategy strategy) {
    return new BeanContainerListener() {
        @Override
        public void created(BeanContainer beanContainer) {
            PersistenceUnitsHolder.initializeJpa(parsedPersistenceXmlDescriptors, scanner, additionalIntegrators,
                    proxyDefinitions, strategy);
        }
    };
}
 
Example #21
Source File: DataSourceTenantConnectionResolver.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns either the default data source or the tenant specific one.
 * 
 * @param tenantId Tenant identifier. The value is required (non-{@literal null}) in case of
 *        {@link MultiTenancyStrategy#DATABASE}.
 * @param strategy Current multitenancy strategy Required value that cannot be {@literal null}.
 * 
 * @return Data source.
 */
private static AgroalDataSource tenantDataSource(JPAConfig jpaConfig, String tenantId, MultiTenancyStrategy strategy) {
    if (strategy != MultiTenancyStrategy.SCHEMA) {
        return Arc.container().instance(AgroalDataSource.class, new DataSource.DataSourceLiteral(tenantId)).get();
    }
    String dataSourceName = jpaConfig.getMultiTenancySchemaDataSource();
    if (dataSourceName == null) {
        AgroalDataSource dataSource = Arc.container().instance(AgroalDataSource.class).get();
        return createFrom(dataSource.getConfiguration());
    }
    return Arc.container().instance(AgroalDataSource.class, new DataSource.DataSourceLiteral(dataSourceName)).get();
}
 
Example #22
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 #23
Source File: AbstractDelegatingSessionFactoryBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public T applyMultiTenancyStrategy(MultiTenancyStrategy strategy) {
	delegate.applyMultiTenancyStrategy( strategy );
	return getThis();
}
 
Example #24
Source File: RecordedState.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public MultiTenancyStrategy getMultiTenancyStrategy() {
    return multiTenancyStrategy;
}
 
Example #25
Source File: SessionFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SessionFactoryBuilder applyMultiTenancyStrategy(MultiTenancyStrategy strategy) {
	this.optionsBuilder.applyMultiTenancyStrategy( strategy );
	return this;
}
 
Example #26
Source File: MetadataBuilderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public MultiTenancyStrategy getMultiTenancyStrategy() {
	return multiTenancyStrategy;
}
 
Example #27
Source File: SessionFactoryOptionsBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void applyMultiTenancyStrategy(MultiTenancyStrategy strategy) {
	this.multiTenancyStrategy = strategy;
}
 
Example #28
Source File: SessionFactoryOptionsBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public MultiTenancyStrategy getMultiTenancyStrategy() {
	return multiTenancyStrategy;
}
 
Example #29
Source File: AbstractDelegatingMetadataBuildingOptions.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public MultiTenancyStrategy getMultiTenancyStrategy() {
	return delegate.getMultiTenancyStrategy();
}
 
Example #30
Source File: AbstractDelegatingSessionFactoryOptions.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public MultiTenancyStrategy getMultiTenancyStrategy() {
	return delegate.getMultiTenancyStrategy();
}