【问题标题】:How to retrieve hibernate.hbm2ddl.auto value from Hibernate at runtime?如何在运行时从 Hibernate 检索 hibernate.hbm2ddl.auto 值?
【发布时间】:2012-09-02 18:43:29
【问题描述】:

我正在尝试解决 Web 应用程序中可能存在的配置错误。我想在运行时从 Hibernate 检索 hibernate.hbm2ddl.auto 值,可以吗? JPA EntityManager 创建成功。

谢谢

【问题讨论】:

  • 我非常怀疑这是否可能!对 Environment 级别属性的任何更改都需要重建 SessionFactory,因为它是不可变的,但您可以使用 Environment 类,重新实例化 SessionFactory,并将您自己的 hbm2ddl.auto 的 java.util.Properties 版本传递给 Configuration.buildSessionFactory( )。
  • 你只是想读取属性值吗?
  • @Narayan:看来 OP 只是想知道属性值,而不是更改它。
  • @davidbuzatto 是的,只读。

标签: java hibernate configuration


【解决方案1】:

检查源代码后,用于构建SessionFactory 的所有配置参数都将存储在其Settings 属性中。

给定EntityManager 的实例,您可以通过以下代码获取用于构建它的SessionFactory

Session session = entityManager.unwrap(Session.class);
SessionFactoryImpl sessionImpl = (SessionFactoryImpl)session.getSessionFactory();

并从 SessionFactoryImpl 中获取 Settings 实例:

Settings setting = sessionImpl.getSettings();

但是,根据以下code 的配置参数如何构建这个Settings 实例:

Settings settings = new Settings();
String autoSchemaExport = properties.getProperty( Environment.HBM2DDL_AUTO );
    if ( "validate".equals(autoSchemaExport) ) {
        settings.setAutoValidateSchema( true );
    }
    if ( "update".equals(autoSchemaExport) ) {
        settings.setAutoUpdateSchema( true );
    }
    if ( "create".equals(autoSchemaExport) ) {
        settings.setAutoCreateSchema( true );
    }
    if ( "create-drop".equals( autoSchemaExport ) ) {
        settings.setAutoCreateSchema( true );
        settings.setAutoDropSchema( true );
    }

hibernate.hbm2ddl.auto 的实际值不会存储在Settings 实例中。它只能解析为 autoDropSchemaautoCreateSchemaautoValidateSchema 的不同值。您必须使用这些属性来确定 hibernate.hbm2ddl.auto 的实际值

【讨论】:

    【解决方案2】:

    要读取配置属性,您可以尝试以下操作:

    AnnotationConfiguration conf = new AnnotationConfiguration().configure();
    String confValue = conf.getProperty( "hibernate.hbm2ddl.auto" );
    

    【讨论】:

    • 据我了解,OP 似乎希望从 EntityManager 的实例中获取 hibernate.hbm2ddl.auto 的值,而不是从配置文件中获取。
    猜你喜欢
    • 2019-01-13
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 2021-02-14
    • 2010-11-17
    • 1970-01-01
    相关资源
    最近更新 更多