我正在使用 Hibernate 租赁,每次用户登录时,我都会将数据库更改为他的用户名(SQLite)。可悲的是,有时数据库不存在,我需要创建它。
问题是我不知道如何在运行时在数据库中创建所有表。
通常 Hibernete 用这个为我创建数据库:
<property name="hibernate.hbm2ddl.auto">update</property>
您可以在运行时通过createDatabaseIfNotExist=true
在 DB 连接 URL 中添加参数来创建数据库。
有关更多信息,请查看SO 链接!
为此,您可以使用 SchemaExport 在创建数据库后立即导出要在新创建的数据库中创建的实体。基本步骤如下。如何获取配置的属性并不重要。
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 在这里: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