java - 使用编程配置 hibernate ,启动 hibernate.hbm2ddl.auto

标签 java database hibernate hbm2ddl sessionfactory

我正在以编程方式配置我的 hibernate session 工厂:

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 的 hibernate 操作时加载。

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

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

建议或其他选择、想法?

最佳答案

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

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

使用像 hibernate.propertieshibernate.cfg.xml 这样的配置文件是设置您的设置的首选方式。

关于java - 使用编程配置 hibernate ,启动 hibernate.hbm2ddl.auto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12636015/

相关文章:

mysql - 对表格进行排序

c# - 部署带有数据库的 C# 程序以在 LAN 上工作的建议

java - 保存对象的 toString 值时出现 Stackoverflow 错误 - Java/Hibernate/Spring

java - 使用 java servlet 重定向响应中丢失 HTTP 自定义 header

java - 通过递归查找 Char 数组中的字符序列

java - 登录表单 : Compare username & password from database

mysql - Select Projections.constructor 中的子查询

java - JPA 的@UniqueConstraint 注释似乎不能保证唯一性

hibernate - 弃用后实现 Hibernate UserType 的最佳方法?

java - 将图像旋转 90 度或倍数的更快方法