Wednesday, March 4, 2015

A Simple Multi-Tenancy Implementation with Hibernate and Spring

For our implementation of the multi-tenant application, Each tenant's data is kept in a physically separate database instance. For each database instance a connection pool is set up when the application starts. For any http request that is not authenticated, a default connection pool is used, pointing to where the user login info is stored. After login the tenant identifier is stored in the Spring Authentication object, so that the corresponding connection pool for that user can be identified. For Spring Security login, we use hibernate, entity manager, and UserDetailService for user authentication.

The User class implements UserDetails interface, so that after user is authenticated we can retrieve this user instance from security context.



For Spring Security, we have to implements UserDetailService.


Then we have to config Persistence configurations.


Notice that we don't have to config a DataSource bean. Instead, we added additional configuration properties for hibernate. We have to create both MyTenantIdentifierResolver and MyMultiTenantConnectionProvider.

First let's look at the MyTenantIdentifierResolver, which essentially output a string for MyMultiTenantConnectionProvider class to choose the right connection pool.


Inside MyMultiTenantConnectionProvider, we first initialize a map containing all connection pools for all tenant. For the overridden method selectConnectionProvider(String s), the input string is provided by MyTenantIdentifierResolver, and the output is a ConnectionProvider object containing a datasource for the specific tenant.



Lastly all we need to define is a custom ConnectionProvider to hold a DataSource.

1 comment: