【问题标题】:manual initialization of required Hibernate database tables手动初始化所需的 Hibernate 数据库表
【发布时间】:2009-05-18 22:02:03
【问题描述】:
我刚开始使用 Hibernate,到目前为止还不算太难。但我对 hbm2ddl.auto 属性感到困惑。有没有办法手动执行初始化数据库表的任何操作?我只想在更改数据库后执行此操作,而不是每次运行程序时执行此操作。
编辑:在运行时呢?我的 Java 程序中有没有办法以编程方式重新初始化数据库表? org.hibernate.tool.hbm2ddl.SchemaUpdate 看起来可能是正确的野兽,但我不确定它到底做了什么。
【问题讨论】:
标签:
hibernate
initialization
hbm2ddl
【解决方案1】:
我会使用 HBM2DDL 生成数据库,然后使用数据库中存在的任何复制/备份来保存数据库模式,并在需要时使用该脚本重新创建数据库;仅在对象模型更改时运行 HBM2DDL 以生成数据库。
【解决方案3】:
好的,感谢您提供的所有线索!以下工作:
public class HibernateUtil {
...
public static SessionFactory createSessionFactory(Properties p)
{
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration cfg = new AnnotationConfiguration().configure();
if (p != null)
cfg.addProperties(p);
return cfg.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
然后在我的应用程序代码中:
private void init() {
Properties p = new Properties();
p.setProperty("hibernate.hbm2ddl.auto", "create");
Session session = HibernateUtil.createSessionFactory(p)
.getCurrentSession();
session.beginTransaction();
session.getTransaction().commit();
session.getSessionFactory().close();
System.out.println("should be initialized....");
}
【解决方案4】:
使用此属性集,您可以为数据库生成创建/更新脚本并执行它们。这是一个很好的原型设计工具,但一段时间后我建议改用另一种数据库更新策略。