How to create database in Hibernate at runtime?

后端 未结 3 1041
盖世英雄少女心
盖世英雄少女心 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:14

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

    For more information check the SO Link !

    0 讨论(0)
  • 2020-12-19 21:18

    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

    0 讨论(0)
  • 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);
        <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

    0 讨论(0)
提交回复
热议问题