【问题标题】:Hibernate configuration on runtime运行时的休眠配置
【发布时间】:2010-11-23 10:25:50
【问题描述】:

我有 hibernate.cfg.xml 文件。

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url"></property>
    <property name="connection.username"></property>
    <property name="connection.password"></property> 

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

.....................

这是文件中最有趣的部分。 现在我必须设置缺失值:url、用户名、密码。 我正在尝试这样做:

public static void SetSessionFactory() {
    try {

      AnnotationConfiguration conf = new AnnotationConfiguration().configure();
      // <!-- Database connection settings -->
      conf.setProperty("connection.url", URL);
      conf.setProperty("connection.username", USERNAME);
      conf.setProperty("connection.password", PASSWORD);
      SESSION_FACTORY = conf.buildSessionFactory();

    } catch (Throwable ex) {
      // Log exception!
      throw new ExceptionInInitializerError(ex);
    }
  }

但它只是从 hibernate.cfg.xm 加载我的配置并且不更改任何属性...

url、username、passoword - 是命令行参数,所以我必须在运行时设置它们。

【问题讨论】:

  • 我应该使用哪个命名空间来在 asp.net MVC 中使用 "AnnotationConfiguration" ?

标签: java hibernate


【解决方案1】:

尝试在此处致电conf.configure();。
并且属性可能需要具有休眠前缀,例如“hibernate.connection.username”
希望对您有所帮助。

【讨论】:

  • maaaaaagic ^_^ 添加了休眠功能。到 cfg 文件和 SetSessionFactory 方法中的属性名称,现在一切正常!
【解决方案2】:

这样试试效果很好

AnnotationConfiguration conf = new AnnotationConfiguration().configure("/dronehibernate.cfg.xml");

conf.setProperty("hibernate.connection.url","jdbc:mysql://localhost/PAT_DRONE_DB1");

SessionFactory sessionFactory = conf.buildSessionFactory();

Session session = sessionFactory.openSession();

List<NetworkType> channelList = session.createQuery("from NetworkType").list();

【讨论】:

    【解决方案3】:

    使用来自Environment 类的常量

    【讨论】:

      猜你喜欢
      • 2015-07-19
      • 2010-11-08
      • 2015-03-16
      • 2015-07-28
      • 2016-05-06
      • 2018-10-21
      • 2012-11-19
      • 2011-01-05
      • 2010-12-26
      相关资源
      最近更新 更多