0

I need to create a session factory for hibernate, but by default it looks for "hibernate.cfg.xml" file. I did not create this file. All hibernate config is in "applicationContext.xml" file of Spring MVC config. All I need to do is provide "/WEB-INF/applicationContext" file path to the "configure" method of Configuration class, but I don't know how find the relative path to this file in JAVA.

        public static SessionFactory createSessionFactory() {
            Configuration configuration = new Configuration();
            configuration.configure(HERE I NEED TO GET "/WEB-INF/applicationContext.xml FILE PATH");
            serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            return sessionFactory;  }
ozsenegal
  • 4,055
  • 12
  • 49
  • 64
  • It looks like you're trying to fetch a `Spring` configuration file to `Hibernate`? Not sure if that's right...you should probably try to load spring application context using spring configuration and then configure your entity manager factory using spring – Zilvinas May 18 '16 at 16:25
  • Please, add `applicationContext.xml` to the question. I think, you try to do an incorrect thing. – v.ladynev May 19 '16 at 08:19

2 Answers2

1

Hibernate loads /WEB-INF/applicationContext.xml using ClassLoader.getResourceAsStream("/WEB-INF/applicationContext.xml")

ClassLoader tries to get access to the files in the root of the classpath — for the web-applications it is war/WEB-INF/classes/. You should put applicationContext.xml to the war/WEB-INF/classes/applicationContext.xml and load it using

sessionFactory = new Configuration().configure("applicationContext.xml")
  .buildSessionFactory();

You can't specify /WEB-INF/applicationContext.xml, because of /WEB-INF/ is not in the class path.

How Hibernate loads resources

If you really want to get a configuration from /WEB-INF/applicationContext.xml you should get URL of applicationContext.xml using ServletContext: File path to resource in our war/WEB-INF folder?

And pass that URL to the Configuration or StandardServiceRegistryBuilder, it depends of Hibernate version.

An important notice

I think, above is senseless, because of applicationContext.xml should has a structure like hibernate.cfg.xml and it, obviously, doesn't.

Community
  • 1
  • 1
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
0

The file should be in your classpath, so you should be able to reference it using the classpath variable: classpath:/WEB-INF/applicationContext.xml

If this won't work then you load the file using class loader and then "ask" for the full path ( this should not be necessary though... ):

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource( "WEB-INF/applicationContext.xml" );
String fullPath = resource.getPath()
Zilvinas
  • 5,518
  • 3
  • 26
  • 26