Hibernate configuration on runtime

社会主义新天地 提交于 2019-11-27 01:08:47

问题


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.


回答1:


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




回答2:


Try like this it is working fine

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:


Use constants from Environment class



来源:https://stackoverflow.com/questions/1341871/hibernate-configuration-on-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!