【问题标题】:Hibernate using Programmatic Configuration, starting hibernate.hbm2ddl.autoHibernate 使用 Programmatic Configuration,启动 hibernate.hbm2ddl.auto
【发布时间】:2012-09-20 02:28:04
【问题描述】:

我正在以编程方式配置我的休眠会话工厂:

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html#configuration-programmatic

private static SessionFactory buildSessionFactory() {

        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure();

        configuration.setProperty("hibernate.connection.url", myUrl);
        configuration.setProperty("hibernate.connection.username", myUser);
        configuration.setProperty("hibernate.connection.password", myPass);

        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); 

        return configuration.buildSessionFactory(serviceRegistry);
}

但问题是,这些属性仅在使用来自 dao 的休眠操作时才加载。

protected void startOperation() {
    session = HibernateUtil.getSessionFactory().openSession();
    tx = session.beginTransaction();
}

因此,当我的应用程序启动时,hibernate.hbm2ddl.auto 似乎不起作用。我可以以某种方式强制 hibernate.hbm2ddl.auto 在我的程序或任何其他解决方案中启动吗?

建议或其他选择、想法?

【问题讨论】:

    标签: java database hibernate hbm2ddl sessionfactory


    【解决方案1】:

    是的。 new Configuration() 应该从 hibernate.cfg.xml 加载所有属性。

    您的SessionFactory 似乎配置为延迟初始化,只有在调用HibernateUtil.getSessionFactory() 时才会构建。

    如果是控制台程序,在main方法中简单调用SessionFactory.buildSessionFactory()

    如果是web应用,可以使用ServletContextListener.contextInitialized(ServletContextEvent sce)或Spring强制SessionFactory.buildSessionFactory()在服务器启动时执行。

    【讨论】:

      【解决方案2】:

      需要设置hibernate.hbm2ddl.auto或者使用

      configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");
      

      使用 hibernate.propertieshibernate.cfg.xml 等配置文件是设置设置的首选方式。

      【讨论】:

      • Configuration configuration = new Configuration(); 应该加载我现有的 hibernate.cfg.xml,我有并且有一行:<property name="hibernate.hbm2ddl.auto">create</property>
      猜你喜欢
      • 2019-01-09
      • 2019-01-13
      • 2021-10-21
      • 2011-01-02
      • 2018-07-06
      • 2012-11-18
      • 2022-01-14
      • 2011-01-27
      • 2016-09-08
      相关资源
      最近更新 更多