How to load hibernate.cfg.xml from different location

前端 未结 4 1226
说谎
说谎 2021-02-08 08:43

I am creating a jar using hibernate. I have encountered a situation where I need to change a setting (url) often, so I would like to load the hibernate.cfg.xml like

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-08 09:16

    supplementing the accepted answer, You can load hibernate.cfg.xml from a different directory (not necessarily the classpath) using the configure(File configFile) method that takes the hibernateConfig File argument. (note, am using hibernate 4.3.7)

    The advantage is, if you have no access to the war file but can get access to the hibernate file in a different directory, say for maintenance.

    Like this:


    String hibernatePropsFilePath = "/etc/configs/hibernate.cfg.xml";
    File hibernatePropsFile = new File(hibernatePropsFilePath);
    
    Configuration configuration = new Configuration(); 
    configuration.configure(hibernatePropsFile);
    
    StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    
    ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    

提交回复
热议问题