我正在开始使用Hibernate,至今并不难。但是我对hbm2ddl.auto属性感到困惑。有没有办法手动执行这些操作来初始化数据库表?我只想在完成数据库更改后执行此操作,而不是每次运行程序时都执行此操作。手动初始化所需的Hibernate数据库表
编辑:在运行时怎么办?有没有在我的Java程序中以编程方式重新初始化数据库表的方法? org.hibernate.tool.hbm2ddl.SchemaUpdate看起来可能像是正确的野兽,但我不确定它究竟做了什么。
我正在开始使用Hibernate,至今并不难。但是我对hbm2ddl.auto属性感到困惑。有没有办法手动执行这些操作来初始化数据库表?我只想在完成数据库更改后执行此操作,而不是每次运行程序时都执行此操作。手动初始化所需的Hibernate数据库表
编辑:在运行时怎么办?有没有在我的Java程序中以编程方式重新初始化数据库表的方法? org.hibernate.tool.hbm2ddl.SchemaUpdate看起来可能像是正确的野兽,但我不确定它究竟做了什么。
我会用就是hbm2ddl生成数据库,然后使用任何复制/备份存在于您的数据库来保存您的数据库架构,并使用该脚本来重新创建数据库时你需要;只有在对象模型更改时才运行HBM2DDL来生成数据库。
使用Hibernate的Ant任务: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....");
}