This post has been featured on http://in.relation.to/2017/01/23/hibernate-community-newsletter-2017-2/ and http://www.baeldung.com/java-web-weekly-161.
Revision #1 on May 9th, 2018: Save operations were failing, added support for Actor instances to be updated via a PATCH endpoint. Updated Transaction Manager section. Revision #2 on Mar 25th, 2019: Excluded DataSourceTransactionManagerAutoConfiguration from auto-configuration.
1. MULTI-TENANT APPLICATIONS USING SPRING BOOT, JPA, HIBERNATE AND POSTGRES
Multitenancy is an approach in which an instance of an application is used by different customers and thus dropping software development and deployment costs when compared to a single-tenant solution where multiple parts would need to be touched in order to provision new clients or update existing tenants.
There are multiple well known strategies to implement this architecture, ranging from highly isolated (like single-tenant) to everything shared.
In this post I’ll review configuring and implementing a multitenancy solution with multiple databases and one API service using Spring Boot, JPA, Hibernate and Postgres.
- 1. MULTI-TENANT APPLICATIONS USING SPRING BOOT, JPA, HIBERNATE AND POSTGRES
- 2. REQUIREMENTS
- 3. SETUP POSTGRES DVD RENTAL DATABASES
- 4. DIFFERENTIATING THE TENANTS
- 5. CREATE THE SPRING BOOT APP
- 6. THE JPA ENTITIES
- 7. CONFIGURE THE PERSISTENCE LAYER
- 8. THE REST LAYER
- 9. RUNNING THE DEMO SERVICE
- 10. SOURCE CODE
- 11. REFERENCES
- Java 7 or 8.
- Maven 3.2+.
- Familiarity with Spring Framework.
- A Postgres server or Docker host.
3. SETUP POSTGRES DVD RENTAL DATABASES
asimio/db_dvdrental Docker image, created in Integration Testing using Spring Boot, Postgres and Docker, is going to be used to start two containers, one for each tenant, mapped to different Docker host ports:
Another approach would be to create the databases in the same server, but naming them differently while keeping the same schema.
4. DIFFERENTIATING THE TENANTS
Now that the DBs are setup lets differentiate them updating a row in the DB listening on
5532 so it would be clear which one is used depending on tenant information:
5. CREATE THE SPRING BOOT APP
This command will create a Maven project in a folder named
springboot-hibernate-multitenancy with most of the dependencies used in the accompanying source code.
Alternatively, it can also be generated using Spring Initializr tool then selecting Actuator, Web and JPA dependencies as shown below:
Spring Initializr - Generate Spring Boot App - Actuator, Web, JPA
6. THE JPA ENTITIES
Generating the JPA entities from a database schema was also covered in Integration Testing using Spring Boot, Postgres and Docker so I’ll just copy
com.asimio.dvdrental.model package from its Bitbucket accompanying source code to
7. CONFIGURE THE PERSISTENCE LAYER
Since the demo application is going to support multitenancy, the persistence layer needs to be manually configured similarly to any Spring application. It will consist of defining and configuring:
- Hibernate, JPA and datasources properties.
- Datasources beans.
- Entity manager factory bean.
- Transaction manager bean.
- Spring Data JPA and transaction support (through the @Transactional annotation) configuration.
To accomplish so, let’s start with the Spring Boot application entry point to exclude some of the beans AutoConfiguration behavior, you would need to explicitly configure the data sources, Hibernate and JPA-related beans:
com.asimio.demo.rest packages will be scanned for @Component-derived annotated classes.
7.1 HIBERNATE, JPA AND DATASOURCES PROPERTIES
172.16.69.133with your Docker host IP where both Postgres containers are running.
Simple JPA, Hibernate and the datasources configuration properties. No DDL will be generated or executed since the databases schema are already in place. The datasources are prefixed with
multitenancy.dvdrental and read into a Java class attributes thanks to yaml support added to Spring but more on this next.
This is the Java class where all the JPA-related beans are instantiated. @Configuration specifies this class is going to provide @Bean-annotated methods defining beans that will be managed by the Spring container.
Also notice how JpaProperties and MultiTenantDvdRentalProperties instances are injected as a result of @EnableConfigurationProperties annotation in line 4.
JpaProperties is provided by Spring Boot and it will include configuration properties prefixed with
spring.jpa as defined earlier.
MultiTenantDvdRentalProperties is a simple Java class as shown below, created for this demo and will include the properties prefixed with
multitenancy.dvdrental, which is basically tenant information and datasource data to establish connections to the DB.
7.2 THE DATASOURCES BEAN
This is a bean that maps each tenant id with its datasource using an injected instance of the previously described MultiTenantDvdRentalProperties class.
7.3 THE ENTITY MANAGER FACTORY BEAN
To make the entityManagerFactory bean multi-tenant-aware, its configuration properties need to include a multi-tenant strategy, a multi-tenant connection provider and a tenant identifier resolver implementations, that’s what have been configured in lines 26 through 28 along with the JPA properties defined in application.yml and explained here.
As for the multitenancy strategy, Hibernate supports:
|DATABASE||A database per tenant.|
|SCHEMA||A schema per tenant.|
|DISCRIMINATOR||One or multiple table columns used to specify different tenants. Added in Hibernate 5|
A requirement is not to set the datasource to the entityManagerFactory bean because it will be retrieved from the MultiTenantConnectionProvider and CurrentTenantIdentifierResolver implementations detailed next.
This MultiTenantConnectionProvider implementation uses the datasource Map discussed here to locate the expected datasource from the tenant identifier, which is retrieved from a CurrentTenantIdentifierResolver implementation reviewed next.
The CurrentTenantIdentifierResolver implementation used for this demo is a simple one delegating tenant selection to DvdRentalTenantContext static methods, which uses a ThreadLocal reference to store and retrieve tenant data.
One advantage of this approach instead of resolving tenant identifier using a request URL or HTTP Header is that the Repository layer could be tested without the need to start a servlet container.
7.4 THE TRANSACTION MANAGER BEAN
Once again, this is the Java class I have been reviewing where all the JPA-related beans are instantiated.
The important things to notice here is that the txManager bean needs to unwrap the EntityManagerFactory implementation, Hibernate’s SessionFactory in this case, to set the AutodetectDataSource attribute to false, this is a requirement for multitenancy to work using the approach discussed in this post.
This is not true, in fact unwrapping the SessionFactory and setting it to the HibernateTransactionManager instance was causing a
PATCH endpoint in DemoResource.java to fail because there wasn’t a transaction to commit to update an Actor entity.
7.5 CONFIGURE SPRING DATA JPA AND ANNOTATION-DRIVEN TRANSACTIONS
Imported using @ImportResource.
com.asimio.dvdrental.dao package includes the interfaces upon which Spring JPA Data instantiates the Repository (or Dao) beans.
@EnableTransactionManagement or tx:annotation-driven allows the execution of class methods annotated with @Transactional to be wrapped in a DB transaction without the need to manually handling the connection or transaction.
8. THE REST LAYER
The REST layer is going to implement a Demo REST resource to demonstrate the multitenancy approach described in this post. It will consist of the REST resource, a Spring interceptor to select and set the tenant identifier and the configuration to associate the interceptor with the REST resource.
To keep this post and sample code simple I decided to inject the Repository dependency in the REST-related class, in a more serious or complex application, I would suggest to implement a Service class where one or more Repository / Dao dependencies would be used along with an Object Mapper / Converter to prevent leaking the application’s internal model to the resource layer.
This Spring interceptor is going to use a ThreadLocal-based implementation included in DvdRentalTenantContext to set the tenant information passed through an HTTP Header. Another option would be to pass the tenant identifier in the URL or through a BEARER token. Although an interceptor was used for this post, a servlet filter could have been implemented and configured instead.
This configuration is automatically done by Spring Boot but needed to be explicitly configured to associate the DvdRentalMultiTenantInterceptor interceptor with the REST requests.
9. RUNNING THE DEMO SERVICE
Sending a request to the
/demo/1 endpoint implemented in the DemoResource class, passing tenant information in
9.1 TENANT 1
9.2 TENANT 2
Notice how the actor section in the response varies as a different tenant is passed in the
X-TENANT-ID header for each request. Also worth mentioning is that the instance ids for the DemoResource and ActorDao instances are the same, meaning that even though multitenancy has been accomplished, they are still singleton instances for which the correct datasource is used.
In the next post I’ll cover Dynamic Configuration using Spring Cloud Bus and will look back at this entry to demo how updating the datasources list will automatically refresh the persistence layer with a new tenant. Stay tuned, go ahead and sign up to the newsletter to receive updates from this blog when content like this is available.
I hope you find this post informational and useful, thanks for reading and feedback is always appreciated.
10. SOURCE CODE
Accompanying source code for this blog post can be found at:
This website includes affiliate links to Udemy, Amazon, Google, Skillshare. This means if you click an affiliate link and buy a product, I might earn a commission at no extra cost to you.