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.

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.

Multi-tenancy Degrees

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.

2. REQUIREMENTS

  • Java 8 or Java 7. For Java 7, java.version property inside pom.xml needs to be updated accordingly.
  • Maven 3.3.x
  • 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:

docker run -d -p 5432:5432 -e DB_NAME=db_dvdrental -e DB_USER=user_dvdrental -e DB_PASSWD=changeit asimio/db_dvdrental:latest
83c9ac6f53b4995cb38796b70593585fbab8cc7ad15bcc580d28f773d9621055
docker run -d -p 5532:5432 -e DB_NAME=db_dvdrental -e DB_USER=user_dvdrental -e DB_PASSWD=changeit asimio/db_dvdrental:latest
004bf55f9576361bb3a674e31bcb4d6f20ca7c875fe91e146289ec8aaf7abe27

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:




psql -h 172.16.69.133 -p 5532 -U user_dvdrental -d db_dvdrental
psql (9.4.4, server 9.5.3)
WARNING: psql major version 9.4, server major version 9.5.
         Some psql features might not work.
Type "help" for help.

db_dvdrental=> select * from Actor where actor_id = 1;
 actor_id | first_name | last_name |      last_update
----------+------------+-----------+------------------------
        1 | Penelope   | Guiness   | 2013-05-26 14:47:57.62
(1 row)

db_dvdrental=> update actor set first_name = 'Orlando', last_name = 'Otero' where actor_id = 1;
UPDATE 1

db_dvdrental=> \q

5. CREATE THE SPRING BOOT APP

curl "https://start.spring.io/starter.tgz" -d bootVersion=1.4.3.RELEASE -d dependencies=actuator,web,data-jpa -d language=java -d type=maven-project -d baseDir=springboot-hibernate-multitenancy -d groupId=com.asimio.demo.api -d artifactId=springboot-hibernate-multitenancy -d version=0-SNAPSHOT | tar -xzvf -

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 src/main/java folder.

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 a couple of Spring Boot AutoConfiguration behavior, meaning the application would need to explicitly configure the datasources, Hibernate and JPA-related beans:

Application.java:

package com.asimio.demo.main;
...
@SpringBootApplication(
  exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class },
  scanBasePackages = { "com.asimio.demo.config", "com.asimio.demo.rest" }
)
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

com.asimio.demo.config and com.asimio.demo.rest packages will be scanned for @Component-derived annotated classes.

spring:
  autoconfigure:
    exclude:
      - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
      - org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
7.1 HIBERNATE, JPA AND DATASOURCES PROPERTIES

application.yml:

...
spring:
  jpa:
    database: POSTGRESQL
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    generate-ddl: false
    hibernate:
      ddl-auto: none
...
multitenancy:
  dvdrental:
    dataSources:
      -
        tenantId: tenant_1
        url: jdbc:postgresql://172.16.69.133:5432/db_dvdrental
        username: user_dvdrental
        password: changeit
        driverClassName: org.postgresql.Driver
      -
        tenantId: tenant_2
        url: jdbc:postgresql://172.16.69.133:5532/db_dvdrental
        username: user_dvdrental
        password: changeit
        driverClassName: org.postgresql.Driver
...

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.

MultiTenantJpaConfiguration.java:

 1 package com.asimio.demo.config.dvdrental;
 2 ...
 3 @Configuration
 4 @EnableConfigurationProperties({ MultiTenantDvdRentalProperties.class, JpaProperties.class })
 5 @ImportResource(locations = { "classpath:applicationContent.xml" })
 6 @EnableTransactionManagement
 7 public class MultiTenantJpaConfiguration {
 8 
 9   @Autowired
10   private JpaProperties jpaProperties;
11 
12   @Autowired
13   private MultiTenantDvdRentalProperties multiTenantDvdRentalProperties;
14 ...
15 }

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.

MultiTenantDvdRentalProperties.java:

package com.asimio.demo.config.dvdrental;
...
@Configuration
@ConfigurationProperties(prefix = "multitenancy.dvdrental")
public class MultiTenantDvdRentalProperties {

  private List<DataSourceProperties> dataSourcesProps;
  // Getters and Setters

  public static class DataSourceProperties extends org.springframework.boot.autoconfigure.jdbc.DataSourceProperties {

    private String tenantId;
    // Getters and Setters
  }
}
7.2 THE DATASOURCES BEAN

MultiTenantJpaConfiguration.java continued:

 1 package com.asimio.demo.config.dvdrental;
 2 ...
 3 @Configuration
 4 @EnableConfigurationProperties({ MultiTenantDvdRentalProperties.class, JpaProperties.class })
 5 @ImportResource(locations = { "classpath:applicationContent.xml" })
 6 @EnableTransactionManagement
 7 public class MultiTenantJpaConfiguration {
 8 ...
 9   @Bean(name = "dataSourcesDvdRental" )
10   public Map<String, DataSource> dataSourcesDvdRental() {
11     Map<String, DataSource> result = new HashMap<>();
12     for (DataSourceProperties dsProperties : this.multiTenantDvdRentalProperties.getDataSources()) {
13       DataSourceBuilder factory = DataSourceBuilder
14         .create()
15         .url(dsProperties.getUrl())
16         .username(dsProperties.getUsername())
17         .password(dsProperties.getPassword())
18         .driverClassName(dsProperties.getDriverClassName());
19       result.put(dsProperties.getTenantId(), factory.build());
20     }
21     return result;
22   }
23 ...
24 }

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

MultiTenantJpaConfiguration.java continued:

 1 package com.asimio.demo.config.dvdrental;
 2 ...
 3 @Configuration
 4 @EnableConfigurationProperties({ MultiTenantDvdRentalProperties.class, JpaProperties.class })
 5 @ImportResource(locations = { "classpath:applicationContent.xml" })
 6 @EnableTransactionManagement
 7 public class MultiTenantJpaConfiguration {
 8 ...
 9   @Bean
10   public MultiTenantConnectionProvider multiTenantConnectionProvider() {
11     // Autowires dataSourcesDvdRental
12     return new DvdRentalDataSourceMultiTenantConnectionProviderImpl();
13   }
14 
15   @Bean
16   public CurrentTenantIdentifierResolver currentTenantIdentifierResolver() {
17     return new TenantDvdRentalIdentifierResolverImpl();
18   }
19 
20   @Bean
21   public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(MultiTenantConnectionProvider multiTenantConnectionProvider,
22     CurrentTenantIdentifierResolver currentTenantIdentifierResolver) {
23 
24     Map<String, Object> hibernateProps = new LinkedHashMap<>();
25     hibernateProps.putAll(this.jpaProperties.getProperties());
26     hibernateProps.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
27     hibernateProps.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
28     hibernateProps.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver);
29 
30     // No dataSource is set to resulting entityManagerFactoryBean
31     LocalContainerEntityManagerFactoryBean result = new LocalContainerEntityManagerFactoryBean();
32     result.setPackagesToScan(new String[] { Actor.class.getPackage().getName() });
33     result.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
34     result.setJpaPropertyMap(hibernateProps);
35 
36     return result;
37   }
38 ...
39 }

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:

Strategy Implementation details
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.

DvdRentalDataSourceMultiTenantConnectionProviderImpl.java:

 1 package com.asimio.demo.config.dvdrental;
 2 ...
 3 public class DvdRentalDataSourceMultiTenantConnectionProviderImpl extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl {
 4 ...
 5   @Autowired
 6   private Map<String, DataSource> dataSourcesDvdRental;
 7 
 8   @Override
 9   protected DataSource selectAnyDataSource() {
10     return this.dataSourcesDvdRental.values().iterator().next();
11   }
12 
13   @Override
14   protected DataSource selectDataSource(String tenantIdentifier) {
15     return this.dataSourcesDvdRental.get(tenantIdentifier);
16   }
17 ...
18 }

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.

TenantDvdRentalIdentifierResolverImpl.java:

 1 package com.asimio.demo.config.dvdrental;
 2 ...
 3 public class TenantDvdRentalIdentifierResolverImpl implements CurrentTenantIdentifierResolver {
 4 
 5   private static String DEFAULT_TENANT_ID = "tenant_1";
 6 
 7   @Override
 8   public String resolveCurrentTenantIdentifier() {
 9     String currentTenantId = DvdRentalTenantContext.getTenantId();
10     return (currentTenantId != null) ? currentTenantId : DEFAULT_TENANT_ID;
11   }
12 ...
13 }

The CurrentTenantIdentifierResolver implementation used for this demo is a simple one delegating tenant selection to DvdRentalTenantContext static methods, which uses the ThreadLocal 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.

DvdRentalTenantContext.java:

 1 package com.asimio.demo.config.dvdrental;
 2 ...
 3 public class DvdRentalTenantContext {
 4 
 5   private static final ThreadLocal<String> CONTEXT = new ThreadLocal<>();
 6 
 7   public static void setTenantId(String tenantId) {
 8     CONTEXT.set(tenantId);
 9   }
10 
11   public static String getTenantId() {
12     return CONTEXT.get();
13   }
14 ...
15 }
7.4 THE TRANSACTION MANAGER BEAN

MultiTenantJpaConfiguration.java continued:

 1 package com.asimio.demo.config.dvdrental;
 2 ...
 3 @Configuration
 4 @EnableConfigurationProperties({ MultiTenantDvdRentalProperties.class, JpaProperties.class })
 5 @ImportResource(locations = { "classpath:applicationContent.xml" })
 6 @EnableTransactionManagement
 7 public class MultiTenantJpaConfiguration {
 8 ...
 9   @Bean
10   public EntityManagerFactory entityManagerFactory(LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
11     return entityManagerFactoryBean.getObject();
12   }
13 
14   @Bean
15   public PlatformTransactionManager txManager(EntityManagerFactory entityManagerFactory) {
16     SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
17     HibernateTransactionManager result = new HibernateTransactionManager();
18     result.setAutodetectDataSource(false);
19     result.setSessionFactory(sessionFactory);
20     return result;
21   }
22 ...
23 }

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.

7.5 CONFIGURE SPRING DATA JPA AND ANNOTATION-DRIVEN TRANSACTIONS

applicationContent.xml:

...
<jpa:repositories base-package="com.asimio.dvdrental.dao" transaction-manager-ref="txManager" />
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />
...

Imported through @ImportResource annotation found in MultiTenantJpaConfiguration class, com.asimio.dvdrental.dao package includes the interfaces upon which Spring JPA Data instantiates the Repository (or Dao) beans.

package com.asimio.dvdrental.dao;
...
public interface ActorDao extends JpaRepository<Actor, Integer> {
}

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.

DemoResource.java:

package com.asimio.demo.rest;
...
@RestController
@RequestMapping(value = "/demo")
@Transactional
public class DemoResource {

  @Autowired
  private ActorDao actorDao;

  @RequestMapping(method = RequestMethod.GET)
  public String getDemo() {
    Actor actor = this.actorDao.getOne(1);
    return String.format("[actor: %s %s], [DemoResource instance: %s], [ActorDao instance: %s]", actor.getFirstName(),
      actor.getLastName(), this, this.actorDao);
  }
...
}

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 Dao dependencies would be used along with an Object Mapper / Converter to prevent leaking the model to the resource layer.

DvdRentalMultiTenantInterceptor.java:

package com.asimio.demo.rest;
...
public class DvdRentalMultiTenantInterceptor extends HandlerInterceptorAdapter {

  private static final String TENANT_HEADER_NAME = "X-TENANT-ID";

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String tenantId = request.getHeader(TENANT_HEADER_NAME);
    DvdRentalTenantContext.setTenantId(tenantId);
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    DvdRentalTenantContext.setTenantId(null);
  }
...
}

This Spring interceptor is going to use the ThreadLocal-based implementation included in DvdRentalTenantContext to set the tenant information passed though 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 used instead.

WebMvcConfiguration.java:

package com.asimio.demo.rest;
...
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new DvdRentalMultiTenantInterceptor());
  }
...
}

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

cd <path to service>/springboot-hibernate-multitenancy/
mvn spring-boot:run

Sending a request to a /demo, resource implemented in the DemoResource class passing tenant information in X-TENANT-ID header:

9.1 TENANT 1
curl -v -H "X-TENANT-ID: tenant_1" "http://localhost:8800/demo"
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8800 (#0)
> GET /demo HTTP/1.1
> Host: localhost:8800
> User-Agent: curl/7.51.0
> Accept: */*
> X-TENANT-ID: tenant_1
>
< HTTP/1.1 200
< X-Application-Context: application:8800
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 193
< Date: Sat, 07 Jan 2017 04:43:47 GMT
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
[actor: Penelope Guiness], [DemoResource instance: com.asimio.demo.rest.DemoResource@6b2e9db2], [ActorDao instance: org.springframework.data.jpa.repository.support.SimpleJpaRepository@7e970e0c]
9.2 TENANT 2
curl -v -H "X-TENANT-ID: tenant_2" "http://localhost:8800/demo"
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8800 (#0)
> GET /demo HTTP/1.1
> Host: localhost:8800
> User-Agent: curl/7.51.0
> Accept: */*
> X-TENANT-ID: tenant_2
>
< HTTP/1.1 200
< X-Application-Context: application:8800
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 190
< Date: Sat, 07 Jan 2017 04:39:18 GMT
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
[actor: Orlando Otero], [DemoResource instance: com.asimio.demo.rest.DemoResource@6b2e9db2], [ActorDao instance: org.springframework.data.jpa.repository.support.SimpleJpaRepository@7e970e0c]

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:

11. REFERENCES