How to create database in Hibernate at runtime?

后端 未结 3 1162
盖世英雄少女心
盖世英雄少女心 2020-12-19 20:42

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.<

3条回答
  •  醉话见心
    2020-12-19 21:25

    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);
        
        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

提交回复
热议问题