Location of Hibernate.Cfg.Xml in Project

Location of hibernate.cfg.xml in project?

Give the path relative to your project.

Create a folder called resources in your src and put your config file there.

   configuration.configure("/resources/hibernate.cfg.xml");

And If you check your code

Configuration  configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return new Configuration().configure().buildSessionFactory();

In two lines you are creating two configuration objects.

That should work(haven't tested) if you write,

Configuration  configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return configuration.buildSessionFactory();

But It fails after you deploy on the server,Since you are using system path than project relative path.

Where to place hibernate.cfg.xml?

The config file hibernate.cfg.xml needs to be on the classpath.

This can be accomplished in different ways, depending on your project.

  • For a web-app WAR project (you are running the program in a Servlet container):
    placing it in WEB-INF/classes will work as files in WEB-INF/classes are visible on the classpath when app is running in container.

  • For a Maven-style project (not running the program in a Servlet container): placing it in /src/main/resources/ will work

  • For otherwise, try in the src/ directory.

web application - where to place hibernate.cfg.xml file?

I always put it into WEB-INF/classes directory (compiled files are stored there).

Hibernate file location in maven web application

create at src/main/resources/hibernate.cfg.xml the project structure should be like this Sample Image
you can follow this link for further clarification

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

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;
}


Related Topics



Leave a reply



Submit