1. Introduction
Multitenancy allows multiple clients or tenants use a single resource or, in the context of this article, a single database instance. The purpose is to isolate the information each tenant needs from the shared database.
In this tutorial, we’ll introduce various approaches to configuring multitenancy in Hibernate 6.
2. Maven Dependencies
We’ll need to include the hibernate-core dependency in the pom.xml file:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.7.Final</version>
</dependency>
For testing, we’ll use an H2 in-memory database, so let’s also add this dependency to the pom.xml file:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</dependency>
3. Understanding Multitenancy in Hibernate
As mentioned in the official Hibernate User Guide, there are three approaches to multitenancy in Hibernate:
- Separate Schema – one schema per tenant in the same physical database instance
- Separate Database – one separate physical database instance per tenant
- Partitioned (Discriminator) Data – the data for each tenant is partitioned by a discriminator value
As usual, Hibernate abstracts the complexity around the implementation of each approach.
All we need is to provide an implementation of these two interfaces:
- MultiTenantConnectionProvider – provides connections per tenant
- CurrentTenantIdentifierResolver – resolves the tenant identifier to use
Let’s see more in detail each concept before going through the database and schema approaches examples.
3.1. MultiTenantConnectionProvider
Basically, this interface provides a database connection for a concrete tenant identifier.
Let’s see its two main methods:
interface MultiTenantConnectionProvider extends Service, Wrapped {
Connection getAnyConnection() throws SQLException;
Connection getConnection(String tenantIdentifier) throws SQLException;
// ...
}
If Hibernate cannot resolve the tenant identifier to use, it will use the method getAnyConnection to get a connection. Otherwise, it will use the method getConnection.
Hibernate provides two implementations of this interface depending on how we define the database connections:
- Using DataSource interface from Java – we would use the DataSourceBasedMultiTenantConnectionProviderImpl implementation
- Using the ConnectionProvider interface from Hibernate – we would use the AbstractMultiTenantConnectionProvider implementation
3.2. CurrentTenantIdentifierResolver
There are many possible ways to resolve a tenant identifier. For example, our implementation could use one tenant identifier defined in a configuration file.
Another way could be to use the tenant identifier from a path parameter.
Let’s see this interface:
public interface CurrentTenantIdentifierResolver {
String resolveCurrentTenantIdentifier();
boolean validateExistingCurrentSessions();
}
Hibernate calls the method resolveCurrentTenantIdentifier to get the tenant identifier. If we want Hibernate to validate all the existing sessions belong to the same tenant identifier, the method validateExistingCurrentSessions should return true.
4. Schema Approach
In this strategy, we’ll use different schemas or users in the same physical database instance. This approach should be used when we need the best performance for our application and can sacrifice special database features such as backup per tenant.
Also, we’ll mock the CurrentTenantIdentifierResolver interface to provide one tenant identifier as our choice during the test:
public abstract class MultitenancyIntegrationTest {
@Mock
private CurrentTenantIdentifierResolver currentTenantIdentifierResolver;
private SessionFactory sessionFactory;
@Before
public void setup() throws IOException {
MockitoAnnotations.initMocks(this);
when(currentTenantIdentifierResolver.validateExistingCurrentSessions())
.thenReturn(false);
Properties properties = getHibernateProperties();
properties.put(
AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER,
currentTenantIdentifierResolver);
sessionFactory = buildSessionFactory(properties);
initTenant(TenantIdNames.MYDB1);
initTenant(TenantIdNames.MYDB2);
}
protected void initTenant(String tenantId) {
when(currentTenantIdentifierResolver
.resolveCurrentTenantIdentifier())
.thenReturn(tenantId);
createCarTable();
}
}
Our implementation of the MultiTenantConnectionProvider interface will set the schema to use every time a connection is requested:
public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
private final ConnectionProvider connectionProvider;
public SchemaMultiTenantConnectionProvider() throws IOException {
connectionProvider = initConnectionProvider();
}
@Override
protected ConnectionProvider getAnyConnectionProvider() {
return connectionProvider;
}
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
return connectionProvider;
}
@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
Connection connection = super.getConnection(tenantIdentifier);
connection.createStatement()
.execute(String.format("SET SCHEMA %s;", tenantIdentifier));
return connection;
}
private ConnectionProvider initConnectionProvider() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
Map<String, Object> configProperties = new HashMap<>();
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
configProperties.put(key, value);
}
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(configProperties);
return connectionProvider;
}
}
So, we’ll use one in-memory H2 database with two schemas – one per each tenant.
Let’s configure the hibernate.properties to use the schema multitenancy mode and our implementation of the MultiTenantConnectionProvider interface*:*
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;\
INIT=CREATE SCHEMA IF NOT EXISTS MYDB1\\;CREATE SCHEMA IF NOT EXISTS MYDB2\\;
hibernate.multiTenancy=SCHEMA
hibernate.multi_tenant_connection_provider=\
com.baeldung.hibernate.multitenancy.schema.SchemaMultiTenantConnectionProvider
For the purposes of our test, we’ve configured the hibernate.connection.url property to create two schemas. This shouldn’t be necessary for a real application since the schemas should be already in place.
For our test, we’ll add one Car entry in the tenant myDb1. We’ll verify this entry was stored in our database and that it’s not in the tenant myDb2:
@Test
void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() {
whenCurrentTenantIs(TenantIdNames.MYDB1);
whenAddCar("myCar");
thenCarFound("myCar");
whenCurrentTenantIs(TenantIdNames.MYDB2);
thenCarNotFound("myCar");
}
As we can see in the test, we change the tenant when calling to the whenCurrentTenantIs method.
5. Database Approach
The Database multi-tenancy approach uses different physical database instances per tenant. Since each tenant is fully isolated, we should choose this strategy when we need special database features like backup per tenant more than we need the best performance.
For the Database approach, we’ll use the same MultitenancyIntegrationTest class and the CurrentTenantIdentifierResolver interface as above.
For the MultiTenantConnectionProvider interface, we’ll use a Map collection to get a ConnectionProvider per tenant identifier:
public class MapMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
private final Map<String, ConnectionProvider> connectionProviderMap = new HashMap<>();
public MapMultiTenantConnectionProvider() throws IOException {
initConnectionProviderForTenant(TenantIdNames.MYDB1);
initConnectionProviderForTenant(TenantIdNames.MYDB2);
}
@Override
protected ConnectionProvider getAnyConnectionProvider() {
return connectionProviderMap.values()
.iterator()
.next();
}
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
return connectionProviderMap.get(tenantIdentifier);
}
private void initConnectionProviderForTenant(String tenantId) throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId)));
Map<String, Object> configProperties = new HashMap<>();
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
configProperties.put(key, value);
}
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(configProperties);
this.connectionProviderMap.put(tenantId, connectionProvider);
}
}
Each ConnectionProvider is populated via the configuration file hibernate-database-
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:<Tenant Identifier>;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
Finally, let’s update the hibernate.properties again to use the database multitenancy mode and our implementation of the MultiTenantConnectionProvider interface:
hibernate.multiTenancy=DATABASE
hibernate.multi_tenant_connection_provider=\
com.baeldung.hibernate.multitenancy.database.MapMultiTenantConnectionProvider
If we run the exact same test as in the schema approach, the test passes again.
6. Conclusion
This article covers Hibernate 6 support for multitenancy using the separate database and separate schema approaches. We provide very simplistic implementations and examples to probe the differences between these two strategies.
The full code samples used in this article are available on our GitHub project.