运行时的Hibernate配置

我有hibernate.cfg.xml文件。

  com.mysql.jdbc.Driver     1 

…………………

这是文件中最有趣的部分。 现在我必须设置缺失值:url,username,password。 我试图这样做:

 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) { // Log exception! throw new ExceptionInInitializerError(ex); } } 

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

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

尝试调用conf.configure(); 这里。
并且属性可能需要具有hibernate前缀,例如“hibernate.connection.username”
希望能帮助到你。

尝试这样它工作正常

AnnotationConfiguration conf = new

。AnnotationConfiguration()配置( “/ dronehibernate.cfg.xml”);

  conf.setProperty("hibernate.connection.url","jdbc:mysql://localhost/PAT_DRONE_DB1"); SessionFactory sessionFactory = conf.buildSessionFactory(); Session session = sessionFactory.openSession(); List channelList = session.createQuery("from NetworkType").list(); 

使用Environment类中的常量