MAGx2 MAGx2 - 2 years ago 137
Java Question

How to create database in Hibernate at runtime?

I'm using Hibernate tenancy and every time user logs I'm changing database to his username (SQLite). Sadly sometimes the database does not exists and I need to create it.

The problem is that I don't know how to create all tables in database at runtime.

Normally Hibernete creates for me db with this:

<property name="">update</property>

Answer Source

You can use the SchemaExport for this to export the entities you want to create in your newly created database right after you created the database. the basic steps are below. How you get the properties for your config does not really matter.

    Configuration config = new Configuration();
    <set all hibernate properties/datasource here>
    SchemaExport schema = new SchemaExport(config);
    schema.create(true, true);

Javadocs are here:

For options of setting upt the configuration look here.

Edit: I guess a remark that has to be added is that it is considered bad practice to let hibernate handle DB/SCHEMA/TABLE creation in a production environment. Depending on the needs and the viability it might be better practice to save prepared SQL statements for this, or even do it manualy by a DB admin. But since we are all lazy I guess thats not often going to happen. ;D

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download