运行时配置Hibernate [英] Hibernate configuration on runtime

查看:92
本文介绍了运行时配置Hibernate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有hibernate.cfg.xml文件。



 < session-factory> 

<! - 数据库连接设置 - >
< 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连接池(使用内置) - >
< property name =connection.pool_size> 1< / property>

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



这是文件中最有趣的部分。
现在我必须设置缺失值:网址,用户名,密码。
我想这样做:

  public static void SetSessionFactory(){
try {

AnnotationConfiguration conf = new AnnotationConfiguration()。configure();
//<! - 数据库连接设置 - >
conf.setProperty(connection.url,URL);
conf.setProperty(connection.username,USERNAME);
conf.setProperty(connection.password,PASSWORD);
SESSION_FACTORY = conf.buildSessionFactory();

} catch(Throwable ex){
//记录异常!
抛出新的ExceptionInInitializerError(ex);


$ / code>

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



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

解决方案

试着在这里调用 conf.configure(); b属性可能需要有hibernate前缀,如hibernate.connection.username

希望它有帮助。


I have hibernate.cfg.xml file.

<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>

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

This is the most interesting part of file. Now i must set missing values: url, username, password. I'm trying to do in such way:

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);
    }
  }

But it just loads my configuration from hibernate.cfg.xm and do not changing any property...

url, username, passoword - are command-line arguments so i must set them on runtime.

解决方案

Try to call conf.configure(); here.
And properties may need to have hibernate prefix like "hibernate.connection.username"
Hope it helps.

这篇关于运行时配置Hibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆