Search code examples
javahibernate

How a JAR can load the hibernate.cfg.xml external file?


I can't figure out how to pass the hibernate configuration file to JAR program. I get the following error when running the JAR:

org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]

I tried to put the file at the same directory of the JAR, or inside the sub folder resources as it is on the project.

Update: Here is how I'm trying to use:

StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
      .configure() 
      .build();  //exception throw here

sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();

hibernate.cfg.xml file is placed inside resource folder. Works correctly when loaded from the unit test.


Solution

  • The problem was that StandardServiceRegistry was trying to load hibernate.cfg.xml from the resources and the resources were not embedded in JAR.

    I move the configuration file to the sub-folder 'config' and loaded it using File class, like this:

    File config = new File("./config/hibernate.cfg.xml");   
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
        .configure(config) 
        .build();
    try 
    {
        sessionFactory = new MetadataSources(registry)
            .buildMetadata().buildSessionFactory();
    }
    catch (Exception e) {
        e.printStackTrace();
        StandardServiceRegistryBuilder.destroy( registry );
        throw e;
    }