必需的Hibernate数据库表的手动初始化
-
22-08-2019 - |
题
我在开始在Hibernate中,到目前为止,它不是太难。但我困惑的hbm2ddl.auto属性。有没有办法手动执行任何这样做初始化数据库表?我只是想做到这一点后,我做我的数据库变化,而不是每次我跑我的程序的时间。
编辑:怎么样在运行时?有没有在我的Java程序中以编程方式重新初始化数据库表? org.hibernate.tool.hbm2ddl.SchemaUpdate 看起来也许像右边的野兽,但我不知道它正是这么做。
解决方案
我会用就是hbm2ddl生成数据库,然后使用任何复制/备份你的数据库上存在,以节省您的数据库架构,并使用脚本,当您需要重新创建数据库;仅运行就是hbm2ddl以生成数据库,当对象模型的变化。
其他提示
使用休眠蚂蚁任务: https://www.hibernate.org/381.html一>
通过此属性设置,您可以生成数据库创建/更新脚本和执行。这是原型设计一个伟大的工具,但一段时间后,我建议移动到另一个数据库的更新策略。
好,感谢所有的线索!以下工作:
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....");
}
不隶属于 StackOverflow