Review Multitenancy User Guide chapter and migrate all examples to unit tests

This commit is contained in:
Vlad Mihalcea 2016-03-01 07:17:10 +02:00
parent 5d1608717e
commit eb6faaa55c
10 changed files with 408 additions and 153 deletions

View File

@ -23,7 +23,7 @@ include::chapters/query/hql/HQL.adoc[]
include::chapters/query/criteria/Criteria.adoc[]
include::chapters/query/native/Native.adoc[]
include::chapters/query/spatial/Spatial.adoc[]
include::chapters/multitenancy/Multi_Tenancy.adoc[]
include::chapters/multitenancy/MultiTenancy.adoc[]
include::chapters/osgi/OSGi.adoc[]
include::chapters/envers/Envers.adoc[]
include::chapters/portability/Portability.adoc[]

View File

@ -1,18 +1,20 @@
[[multitenacy]]
== Multi-tenancy
:sourcedir: extras
== Multitenancy
:sourcedir: ../../../../../test/java/org/hibernate/userguide/multitenancy
=== What is multi-tenancy?
[[multitenacy-intro]]
=== What is multitenancy?
The term multi-tenancy in general is applied to software development to indicate an architecture in which a single running instance of an application simultaneously serves multiple clients (tenants).
The term multitenancy, in general, is applied to software development to indicate an architecture in which a single running instance of an application simultaneously serves multiple clients (tenants).
This is highly common in SaaS solutions.
Isolating information (data, customizations, etc) pertaining to the various tenants is a particular challenge in these systems.
Isolating information (data, customizations, etc.) pertaining to the various tenants is a particular challenge in these systems.
This includes the data owned by each tenant stored in the database.
It is this last piece, sometimes called multi-tenant data, on which we will focus.
It is this last piece, sometimes called multitenant data, on which we will focus.
=== Multi-tenant data approaches
[[multitenacy-approaches]]
=== Multitenant data approaches
There are three main approaches to isolating information in these multi-tenant systems which goes hand-in-hand with different database schema definitions and JDBC setups.
There are three main approaches to isolating information in these multitenant systems which go hand-in-hand with different database schema definitions and JDBC setups.
[NOTE]
====
@ -21,27 +23,30 @@ Such topics are beyond the scope of this documentation.
Many resources exist which delve into these other topics, like http://msdn.microsoft.com/en-us/library/aa479086.aspx[this one] which does a great job of covering these topics.
====
=== Separate database
[[multitenacy-separate-database]]
==== Separate database
image:images/multitenancy/multitenacy_database.png[]
Each tenant's data is kept in a physically separate database instance.
JDBC Connections would point specifically to each database, so any pooling would be per-tenant.
JDBC Connections would point specifically to each database so any pooling would be per-tenant.
A general application approach, here, would be to define a JDBC Connection pool per-tenant and to select the pool to use based on the _tenant identifier_ associated with the currently logged in user.
=== Separate schema
[[multitenacy-separate-schema]]
==== Separate schema
image:images/multitenancy/multitenacy_schema.png[]
Each tenant's data is kept in a distinct database schema on a single database instance.
There are two different ways to define JDBC Connections here:
* Connections could point specifically to each schema, as we saw with the `Separate database` approach.
* Connections could point specifically to each schema as we saw with the `Separate database` approach.
This is an option provided that the driver supports naming the default schema in the connection URL or if the pooling mechanism supports naming a schema to use for its Connections.
Using this approach, we would have a distinct JDBC Connection pool per-tenant where the pool to use would be selected based on the "tenant identifier" associated with the currently logged in user.
* Connections could point to the database itself (using some default schema) but the Connections would be altered using the SQL `SET SCHEMA` (or similar) command.
Using this approach, we would have a single JDBC Connection pool for use to service all tenants, but before using the Connection it would be altered to reference the schema named by the "tenant identifier" associated with the currently logged in user.
Using this approach, we would have a single JDBC Connection pool for use to service all tenants, but before using the Connection, it would be altered to reference the schema named by the "tenant identifier" associated with the currently logged in user.
[[multitenacy-discriminator]]
=== Partitioned (discriminator) data
image:images/multitenancy/multitenacy_discriminator.png[]
@ -52,27 +57,28 @@ The complexity of this discriminator might range from a simple column value to a
Again, this approach would use a single Connection pool to service all tenants.
However, in this approach the application needs to alter each and every SQL statement sent to the database to reference the "tenant identifier" discriminator.
=== Multi-tenancy in Hibernate
[[multitenacy-hibernate]]
=== Multitenancy in Hibernate
Using Hibernate with multi-tenant data comes down to both an API and then integration piece(s).
As usual Hibernate strives to keep the API simple and isolated from any underlying integration complexities.
Using Hibernate with multitenant data comes down to both an API and then integration piece(s).
As usual, Hibernate strives to keep the API simple and isolated from any underlying integration complexities.
The API is really just defined by passing the tenant identifier as part of opening any session.
[[specifying-tenant-ex]]
.Specifying tenant identifier from [interface]+SessionFactory+
[[multitenacy-hibernate-session-example]]
.Specifying tenant identifier from `SessionFactory`
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/tenant-identifier-from-SessionFactory.java[]
include::{sourcedir}/AbstractMultiTenancyTest.java[tags=multitenacy-hibernate-session-example]
----
====
Additionally, when specifying configuration, a `org.hibernate.MultiTenancyStrategy` should be named using the `hibernate.multiTenancy` setting.
Additionally, when specifying the configuration, an `org.hibernate.MultiTenancyStrategy` should be named using the `hibernate.multiTenancy` setting.
Hibernate will perform validations based on the type of strategy you specify.
The strategy here correlates to the isolation approach discussed above.
NONE::
(the default) No multi-tenancy is expected.
(the default) No multitenancy is expected.
In fact, it is considered an error if a tenant identifier is specified when opening a session using this strategy.
SCHEMA::
Correlates to the separate schema approach.
@ -85,14 +91,17 @@ DATABASE::
DISCRIMINATOR::
Correlates to the partitioned (discriminator) approach.
It is an error to attempt to open a session without a tenant identifier using this strategy.
This strategy is not yet implemented in Hibernate as of 4.0 and 4.1. Its support is planned for 5.0.
This strategy is not yet implemented and you can follow its progress via the https://hibernate.atlassian.net/browse/HHH-6054[HHH-6054 Jira issue].
=== MultiTenantConnectionProvider
[[multitenacy-hibernate-MultiTenantConnectionProvider]]
==== MultiTenantConnectionProvider
When using either the DATABASE or SCHEMA approach, Hibernate needs to be able to obtain Connections in a tenant specific manner.
That is the role of the `MultiTenantConnectionProvider` contract.
When using either the DATABASE or SCHEMA approach, Hibernate needs to be able to obtain Connections in a tenant-specific manner.
That is the role of the `MultiTenantConnectionProvider` contract.
Application developers will need to provide an implementation of this contract.
Most of its methods are extremely self-explanatory.
Most of its methods are extremely self-explanatory.
The only ones which might not be are `getAnyConnection` and `releaseAnyConnection`.
It is important to note also that these methods do not accept the tenant identifier.
Hibernate uses these methods during startup to perform various configuration, mainly via the `java.sql.DatabaseMetaData` object.
@ -104,9 +113,43 @@ It could name a `MultiTenantConnectionProvider` instance, a `MultiTenantConnecti
* Passed directly to the `org.hibernate.boot.registry.StandardServiceRegistryBuilder`.
* If none of the above options match, but the settings do specify a `hibernate.connection.datasource` value,
Hibernate will assume it should use the specific `DataSourceBasedMultiTenantConnectionProviderImpl` implementation which works on a number of pretty reasonable assumptions when running inside of an app server and using one `javax.sql.DataSource` per tenant.
See its https://docs.jboss.org/hibernate/orm/5.0/javadocs/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.html[Javadocs] for more details.
See its https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/javadocs/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.html[Javadocs] for more details.
=== CurrentTenantIdentifierResolver
The following example portrays a `MultiTenantConnectionProvider` implementation that handles multiple `ConnectionProviders`.
[[multitenacy-hibernate-ConfigurableMultiTenantConnectionProvider-example]]
.A `MultiTenantConnectionProvider` implementation
====
[source, JAVA, indent=0]
----
include::{sourcedir}/ConfigurableMultiTenantConnectionProvider.java[tags=multitenacy-hibernate-ConfigurableMultiTenantConnectionProvider-example]
----
====
The `ConfigurableMultiTenantConnectionProvider` can be set up as follows:
[[multitenacy-hibernate-MultiTenantConnectionProvider-example]]
.A `MultiTenantConnectionProvider` implementation
====
[source, JAVA, indent=0]
----
include::{sourcedir}/AbstractMultiTenancyTest.java[tags=multitenacy-hibernate-MultiTenantConnectionProvider-example]
----
====
When using multitenancy, it's possible to save an entity with the same identifier across different tenants:
[[multitenacy-hibernate-same-entity-example]]
.A `MultiTenantConnectionProvider` implementation
====
[source, JAVA, indent=0]
----
include::{sourcedir}/AbstractMultiTenancyTest.java[tags=multitenacy-multitenacy-hibernate-same-entity-example]
----
====
[[multitenacy-hibernate-MultiTenantConnectionProvider]]
==== CurrentTenantIdentifierResolver
`org.hibernate.context.spi.CurrentTenantIdentifierResolver` is a contract for Hibernate to be able to resolve what the application considers the current tenant identifier.
The implementation to use is either passed directly to `Configuration` via its `setCurrentTenantIdentifierResolver` method.
@ -114,47 +157,26 @@ It can also be specified via the `hibernate.tenant_identifier_resolver` setting.
There are two situations where CurrentTenantIdentifierResolver is used:
* The first situation is when the application is using the `org.hibernate.context.spi.CurrentSessionContext` feature in conjunction with multi-tenancy.
* The first situation is when the application is using the `org.hibernate.context.spi.CurrentSessionContext` feature in conjunction with multitenancy.
In the case of the current-session feature, Hibernate will need to open a session if it cannot find an existing one in scope.
However, when a session is opened in a multi-tenant environment the tenant identifier has to be specified.
However, when a session is opened in a multitenant environment, the tenant identifier has to be specified.
This is where the `CurrentTenantIdentifierResolver` comes into play; Hibernate will consult the implementation you provide to determine the tenant identifier to use when opening the session.
In this case, it is required that a `CurrentTenantIdentifierResolver` be supplied.
* The other situation is when you do not want to have to explicitly specify the tenant identifier all the time as we saw in <<specifying-tenant-ex>>.
* The other situation is when you do not want to have to explicitly specify the tenant identifier all the time.
If a `CurrentTenantIdentifierResolver` has been specified, Hibernate will use it to determine the default tenant identifier to use when opening the session.
Additionally, if the `CurrentTenantIdentifierResolver` implementation returns `true` for its `validateExistingCurrentSessions` method, Hibernate will make sure any existing sessions that are found in scope have a matching tenant identifier.
This capability is only pertinent when the `CurrentTenantIdentifierResolver` is used in current-session settings.
=== Caching
[[multitenacy-hibernate-caching]]
==== Caching
Multi-tenancy support in Hibernate works seamlessly with the Hibernate second level cache.
Multitenancy support in Hibernate works seamlessly with the Hibernate second level cache.
The key used to cache data encodes the tenant identifier.
=== Odds and ends
Currently schema export will not really work with multi-tenancy. That may not change.
The JPA expert group is in the process of defining multi-tenancy support for an upcoming version of the specification.
=== Strategies for `MultiTenantConnectionProvider` implementors
.Implementing `MultiTenantConnectionProvider` using different connection pools
====
[source,java]
----
include::{sourcedir}/MultiTenantConnectionProviderImpl-multi-cp.java[]
----
[NOTE]
====
Currently, schema export will not really work with multitenancy. That may not change.
The approach above is valid for the DATABASE approach.
It is also valid for the SCHEMA approach provided the underlying database allows naming the schema to which to connect in the connection URL.
.Implementing `MultiTenantConnectionProvider` using single connection pool
The JPA expert group is in the process of defining multitenancy support for an upcoming version of the specification.
====
[source,java]
----
include::{sourcedir}/MultiTenantConnectionProviderImpl-single-cp.java[]
----
====
This approach is only relevant to the SCHEMA approach.

View File

@ -1,28 +0,0 @@
/**
* Simplisitc implementation for illustration purposes supporting
* 2 hard coded providers ( pools ) and leveraging the support class
* {@link org.hibernate.service.jdbc.connections.spi.AbstractMultiTenantConnectionProvider}
*/
public class MultiTenantConnectionProviderImpl extends AbstractMultiTenantConnectionProvider {
private final ConnectionProvider acmeProvider =
ConnectionProviderUtils.buildConnectionProvider( "acme" );
private final ConnectionProvider jbossProvider =
ConnectionProviderUtils.buildConnectionProvider( "jboss" );
@Override
protected ConnectionProvider getAnyConnectionProvider() {
return acmeProvider;
}
@Override
protected ConnectionProvider selectConnectionProvider( String tenantIdentifier ) {
if ( "acme".equals( tenantIdentifier ) ) {
return acmeProvider;
} else if ( "jboss".equals( tenantIdentifier ) ) {
return jbossProvider;
}
throw new HibernateException( "Unknown tenant identifier" );
}
}

View File

@ -1,59 +0,0 @@
/**
* Simplisitc implementation for illustration purposes showing
* a single connection pool used to serve multiple schemas using "connection altering".
* Here we use the T-SQL specific USE command;
* Oracle users might use the ALTER SESSION SET SCHEMA command; etc.
*/
public class MultiTenantConnectionProviderImpl
implements MultiTenantConnectionProvider, Stoppable {
private final ConnectionProvider connectionProvider =
ConnectionProviderUtils.buildConnectionProvider( "master" );
@Override
public Connection getAnyConnection() throws SQLException {
return connectionProvider.getConnection();
}
@Override
public void releaseAnyConnection( Connection connection ) throws SQLException {
connectionProvider.closeConnection( connection );
}
@Override
public Connection getConnection( String tenantIdentifier )
throws SQLException {
final Connection connection = getAnyConnection();
try {
connection.createStatement().execute( "USE " + tenanantIdentifier );
} catch ( SQLException e ) {
throw new HibernateException(
"Could not alter JDBC connection to specified schema [" +
tenantIdentifier + "]",
e
);
}
return connection;
}
@Override
public void releaseConnection( String tenantIdentifier, Connection connection )
throws SQLException {
try {
connection.createStatement().execute( "USE master" );
} catch ( SQLException e ) {
// on error, throw an exception to make sure
// the connection is not returned to the pool.
// your requirements may differ
throw new HibernateException(
"Could not alter JDBC connection to specified schema [" +
tenantIdentifier + "]",
e
);
}
connectionProvider.closeConnection( connection );
}
...
}

View File

@ -1,5 +0,0 @@
Session session = sessionFactory
.withOptions()
.tenantIdentifier( yourTenantIdentifier )
...
.openSession();

View File

@ -69,7 +69,7 @@ It was done here only for completeness of an example.
The `Person_.name` reference is an example of the static form of JPA Metamodel reference.
We will use that form exclusively in this chapter.
See the documentation for the https://docs.jboss.org/hibernate/orm/5.0/topical/html/metamodelgen/MetamodelGenerator.html[Hibernate JPA Metamodel Generator] for additional details on the JPA static Metamodel.
See the documentation for the https://docs.jboss.org/hibernate/orm/{majorMinorVersion}/topical/html/metamodelgen/MetamodelGenerator.html[Hibernate JPA Metamodel Generator] for additional details on the JPA static Metamodel.
====
[[criteria-typedquery-expression]]

View File

@ -0,0 +1,232 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.userguide.multitenancy;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.function.Consumer;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.MultiTenancyStrategy;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.spi.SqlStatementLogger;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.tool.schema.internal.HibernateSchemaManagementTool;
import org.hibernate.tool.schema.internal.SchemaCreatorImpl;
import org.hibernate.tool.schema.internal.SchemaDropperImpl;
import org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase;
import org.hibernate.tool.schema.internal.exec.JdbcConnectionContextNonSharedImpl;
import org.hibernate.testing.boot.JdbcConnectionAccessImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;
/**
* @author Vlad Mihalcea
*/
public abstract class AbstractMultiTenancyTest extends BaseUnitTestCase {
protected static final String FRONT_END_TENANT = "front_end";
protected static final String BACK_END_TENANT = "back_end";
private Map<String, ConnectionProvider> connectionProviderMap = new HashMap<>( );
private SessionFactory sessionFactory;
public AbstractMultiTenancyTest() {
init();
}
//tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[]
private void init() {
registerConnectionProvider( FRONT_END_TENANT );
registerConnectionProvider( BACK_END_TENANT );
Map<String, Object> settings = new HashMap<>( );
settings.put( AvailableSettings.MULTI_TENANT, multiTenancyStrategy() );
settings.put( AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER,
new ConfigurableMultiTenantConnectionProvider( connectionProviderMap ) );
sessionFactory = sessionFactory(settings);
}
//end::multitenacy-hibernate-MultiTenantConnectionProvider-example[]
//tag::multitenacy-hibernate-MultiTenantConnectionProvider-example[]
protected void registerConnectionProvider(String tenantIdentifier) {
Properties properties = properties();
properties.put( Environment.URL,
tenantUrl(properties.getProperty( Environment.URL ), tenantIdentifier) );
DriverManagerConnectionProviderImpl connectionProvider =
new DriverManagerConnectionProviderImpl();
connectionProvider.configure( properties );
connectionProviderMap.put( tenantIdentifier, connectionProvider );
}
//end::multitenacy-hibernate-MultiTenantConnectionProvider-example[]
@Test
public void testBasicExpectedBehavior() {
//tag::multitenacy-multitenacy-hibernate-same-entity-example[]
doInSession( FRONT_END_TENANT, session -> {
Person person = new Person( );
person.setId( 1L );
person.setName( "John Doe" );
session.persist( person );
} );
doInSession( BACK_END_TENANT, session -> {
Person person = new Person( );
person.setId( 1L );
person.setName( "John Doe" );
session.persist( person );
} );
//end::multitenacy-multitenacy-hibernate-same-entity-example[]
}
protected abstract MultiTenancyStrategy multiTenancyStrategy();
protected Properties properties() {
Properties properties = new Properties( );
URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource( "hibernate.properties" );
try(FileInputStream inputStream = new FileInputStream( propertiesURL.getFile() )) {
properties.load( inputStream );
}
catch (IOException e) {
throw new IllegalArgumentException( e );
}
return properties;
}
protected abstract String tenantUrl(String originalUrl, String tenantIdentifier);
protected SessionFactory sessionFactory(Map<String, Object> settings) {
ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) new StandardServiceRegistryBuilder()
.applySettings( settings() )
.build();
MetadataSources metadataSources = new MetadataSources( serviceRegistry );
for(Class annotatedClasses : getAnnotatedClasses()) {
metadataSources.addAnnotatedClass( annotatedClasses );
}
Metadata metadata = metadataSources.buildMetadata();
HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool();
tool.injectServices( serviceRegistry );
final GenerationTargetToDatabase frontEndSchemaGenerator = new GenerationTargetToDatabase(
new JdbcConnectionContextNonSharedImpl(
new JdbcConnectionAccessImpl( connectionProviderMap.get( FRONT_END_TENANT ) ),
new SqlStatementLogger( false, true ),
true
)
);
final GenerationTargetToDatabase backEndSchemaGenerator = new GenerationTargetToDatabase(
new JdbcConnectionContextNonSharedImpl(
new JdbcConnectionAccessImpl( connectionProviderMap.get( BACK_END_TENANT ) ),
new SqlStatementLogger( false, true ),
true
)
);
new SchemaDropperImpl( serviceRegistry ).doDrop(
metadata,
serviceRegistry,
settings,
true,
frontEndSchemaGenerator,
backEndSchemaGenerator
);
new SchemaCreatorImpl( serviceRegistry ).doCreation(
metadata,
serviceRegistry,
settings,
true,
frontEndSchemaGenerator,
backEndSchemaGenerator
);
final SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
return sessionFactoryBuilder.build();
}
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Person.class
};
}
//tag::multitenacy-hibernate-session-example[]
private void doInSession(String tenant, Consumer<Session> function) {
Session session = null;
Transaction txn = null;
try {
session = sessionFactory
.withOptions()
.tenantIdentifier( tenant )
.openSession();
txn = session.getTransaction();
txn.begin();
function.accept(session);
txn.commit();
} catch (Throwable e) {
if ( txn != null ) txn.rollback();
throw e;
} finally {
if (session != null) {
session.close();
}
}
}
//end::multitenacy-hibernate-session-example[]
@Entity(name = "Person")
public static class Person {
@Id
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@ -0,0 +1,40 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.userguide.multitenancy;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
/**
* @author Vlad Mihalcea
*/
//tag::multitenacy-hibernate-ConfigurableMultiTenantConnectionProvider-example[]
public class ConfigurableMultiTenantConnectionProvider
extends AbstractMultiTenantConnectionProvider {
private final Map<String, ConnectionProvider> connectionProviderMap =
new HashMap<>( );
public ConfigurableMultiTenantConnectionProvider(
Map<String, ConnectionProvider> connectionProviderMap) {
this.connectionProviderMap.putAll( connectionProviderMap );
}
@Override
protected ConnectionProvider getAnyConnectionProvider() {
return connectionProviderMap.values().iterator().next();
}
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
return connectionProviderMap.get( tenantIdentifier );
}
}
//end::multitenacy-hibernate-ConfigurableMultiTenantConnectionProvider-example[]

View File

@ -0,0 +1,25 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.userguide.multitenancy;
import org.hibernate.MultiTenancyStrategy;
/**
* @author Vlad Mihalcea
*/
public class DatabaseMultiTenancyTest extends AbstractMultiTenancyTest {
@Override
protected MultiTenancyStrategy multiTenancyStrategy() {
return MultiTenancyStrategy.DATABASE;
}
@Override
protected String tenantUrl(String originalUrl, String tenantIdentifier) {
return originalUrl.replace( "db1", tenantIdentifier );
}
}

View File

@ -0,0 +1,28 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.userguide.multitenancy;
import org.hibernate.MultiTenancyStrategy;
/**
* @author Vlad Mihalcea
*/
public class SchemaMultiTenancyTest extends AbstractMultiTenancyTest {
public static final String SCHEMA_TOKEN = ";INIT=CREATE SCHEMA IF NOT EXISTS %1$s\\;SET SCHEMA %1$s";
@Override
protected MultiTenancyStrategy multiTenancyStrategy() {
return MultiTenancyStrategy.SCHEMA;
}
@Override
protected String tenantUrl(String originalUrl, String tenantIdentifier) {
return originalUrl + String.format( SCHEMA_TOKEN, tenantIdentifier );
}
}