如何在运行时在Hibernate中创建数据库? [英] How to create database in Hibernate at runtime?

查看:103
本文介绍了如何在运行时在Hibernate中创建数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Hibernate租约,每次用户登录时,我都将数据库更改为他的用户名(SQLite)。可悲的是,有时数据库不存在,我需要创建它。



问题是我不知道如何在运行时创建数据库中的所有表。

p>

通常情况下,Hibernete会为我创建db:

 <属性名称= hibernate.hbm2ddl.auto >更新< /性> 


解决方案

您可以使用SchemaExport来导出实体您希望在创建数据库后立即在新创建的数据库中创建。基本步骤如下。如何获得配置的属性并不重要。

 配置config = new Configuration(); 
config.addAnnotatedClass(Class1.class);
config.addAnnotatedClass(Class2.class);
config.addAnnotatedClass(Class3.class);
<在此设置所有hibernate属性/数据源>
SchemaExport schema = new SchemaExport(config);
schema.create(true,true);

Javadocs在这里: http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/tool/hbm2ddl/ SchemaExport.html



有关设置配置的选项,请看这里。 http://docs.jboss.org/hibernate /orm/3.3/api/org/hibernate/cfg/Configuration.html



编辑:
我猜必须添加一句话是让休眠处理生产环境中的DB / SCHEMA / TABLE创建被认为是不好的做法。根据需要和可行性,为此可以更好地保存准备好的SQL语句,甚至可以通过数据库管理员进行手动操作。但因为我们都很懒惰,我猜这种情况不会经常发生。 ; D

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>

解决方案

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

这篇关于如何在运行时在Hibernate中创建数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆