Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating databases at runtime with Hibernate?

Is it possible to use Hibernate to, at runtime, create a new database (using the annotations of the model objects as schema, or from a normal schema file we define), and then get a connection to that database so that it can be used?

What we would like to do is, when a certain action happens (for instance a new user is created), we create a new databse for that user (from the defined annotations or simply a static schema), and then have a handle to that database so the user can write to it.

The user thing is simply for illustrating the concept...

Thanks!

like image 692
Nico Huysamen Avatar asked Jan 20 '23 20:01

Nico Huysamen


2 Answers

At a high-level, what you would do to accomplish something like this is:

  1. When the trigger event happens, execute the DDL to create a new database through a JDBC connection - probably makes the most sense for this schema to be generated by hbm2ddl at build-time.

  2. Construct a new DataSource for this database, and a new SessionFactory from the DataSource

  3. This SessionFactory should then be injected into (or looked up by) the data-access layer of your application, to find the appropriate SessionFactory for the User.

In short, the answer is to construct SessionFactory instances dynamically for each connection/database and make sure that your data-access layer knows how to find the appropriate SessionFactory for the criteria.

like image 141
matt b Avatar answered Jan 28 '23 11:01

matt b


Agree with matt b, but are you sure it's a good idea to do such a thing?

I guess you have different customers and want to store each one's data in a separate database (or something like that). Why not storing all customers data in the same database, and filter these data by the customer id?

like image 20
Sebastien Lorber Avatar answered Jan 28 '23 13:01

Sebastien Lorber