运行时休眠配置

2022-09-03 05:33:56

我有休眠.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);
    }
  }

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

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


答案 1

尝试拨打此处。
属性可能需要具有休眠前缀,如“hibernate.connection.username”
希望它有所帮助。conf.configure();


答案 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();

推荐