1
votes

I stucked with a serious problem in architecture of my enterprise application. My current application is a web application using spring framework 3.2+ and jpa 2.0. Now I need to support multi tenancy in current application.

My requirement is that when a user logged in to the system the data for the user should be served from respective database. In short I need multiple database support which may cause different connection string. So how can I connect to database dynamically?

My another problem is that tenant (particular client of the applications) can register himself on the fly, and on successful registration I need to create a environment containing database creation and initialization etc. for that tenant and on successful creation of environment users of tenants are able to access the application. So problem is how to create environment dynamically, how create EntityManagerFactory dynamically?

Any suggestions to achieve the multi tenancy are most welcome...

1
Assuming that you use Hibernate as your provider the newer versions have multitenant support out-of-the-box. Otherwise you can use something like this (Shameless plug) which we used for multitenancy support (which is still running in production after about 8 years). - M. Deinum
Yes, I'm using hibernate as a provider, But it may change in future. - Mitesh

1 Answers

0
votes

In a web environment, the multi-tenancy can be implemented with the creation of tenant-specific aliases to be defined in your /etc/hosts file or Windows\System32\drivers\etc\hosts in order to map tenant-specific hosts to the same servlet container.

Once you've done that you can define a servlet filter which gonna read the current used host and compare it to another mapping, to be defined in a properties file, for example, and populate a HTTP session parameter indicating the current tenant.

Here you've got the tenant in the session.

You have to target a common database and a specific 'tenant_database' table. This table must hold the database name, the password, the port, etc. All the datasource information to establish the connection to a targeted tenant database.

You can build an entityManagerFactory at this point:

  Map<String, String> properties = new HashMap<String, String>();
  properties.put("javax.persistence.jdbc.user", "admin");
  properties.put("javax.persistence.jdbc.password", "admin");
  EntityManagerFactory emf = Persistence.createEntityManagerFactory(
      "jdbc:mysql://localhost:3306/myDB", properties);

You just have to think about obtaining it from the right place now.. :)

Hope it helps