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...
T开发者_开发技巧hanks!
At a high-level, what you would do to accomplish something like this is:
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.Construct a new
DataSource
for this database, and a newSessionFactory
from theDataSource
This
SessionFactory
should then be injected into (or looked up by) the data-access layer of your application, to find the appropriateSessionFactory
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.
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?
I've followed a discussion in my company some times ago and they were talking about spring support for doing that.
Some things that could interest you: http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/ http://static.springsource.org/spring/docs/3.0.x/javadoc-api/index.html?org/springframework/aop/target/HotSwappableTargetSource.html
AbstractRoutingDataSource seems to be interesting for your case. Someone also said that this perhaps disable the 2nd hibernate cache, to confirm...
I come back a little late but if you'r planning to build a multi tenancy SAAS application, as you said, you could also use a separation by key like customer id.
In hibernate, the filters help you to do that...
See: http://www.lunatech-research.com/archives/2011/03/04/play-framework-writing-multitenancy-application-hibernate-filters
It's a link for play framework but it uses hibernate so you could do almost the same with classic Java EE stuff...
精彩评论