简体   繁体   中英

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="hibernate.hbm2ddl.auto">update</property>

Did you try the value create instead.

A value of create will create your tables at sessionFactory creation, and leave them intact.

A value of create-drop will create your tables, and then drop them when you close the sessionFactory.

That would be

<property name="hibernate.hbm2ddl.auto">create</property>

More infornation here and here
Or there could be a dialect problem

You can create database at run time by adding createDatabaseIfNotExist=true parameter in DB connection URL.

For more information check the SO Link !

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();
    config.addAnnotatedClass(Class1.class);
    config.addAnnotatedClass(Class2.class);
    config.addAnnotatedClass(Class3.class);
    <set all hibernate properties/datasource here>
    SchemaExport schema = new SchemaExport(config);
    schema.create(true, true);

Javadocs are here: http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/tool/hbm2ddl/SchemaExport.html

For options of setting upt the configuration look here. http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/cfg/Configuration.html

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM