How to load hibernate.cfg.xml from different directory

November 24, 2014 0 Comments

Hibernate XML configuration file “hibernate.cfg.xml” is always put at the root of your project classpath, outside of any package. If you place this configuration file into a different directory, you may encounter the following error :
 at com.mkyong.common.App.main(
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
 at org.hibernate.util.ConfigHelper.getResourceAsStream(
 at org.hibernate.cfg.Configuration.getConfigurationInputStream(
 at org.hibernate.cfg.Configuration.configure(
 at org.hibernate.cfg.Configuration.configure(
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(
 ... 2 more

To ask Hibernate look for your “hibernate.cfg.xml” file in other directory, you can modify the default Hibernate’s SessionFactory class by passing your “hibernate.cfg.xml” file path as an argument into the configure() method:
SessionFactory sessionFactory = new AnnotationConfiguration().configure("/conf/hibernate.cfg.xml").buildSessionFactory();

Another alternate way to load “hibernate.cfg.xml” file is by using absolute path as below
 File f = new File("D:\\Workspace\\Kepler\\HibernateExamples\\conf\\hibernate.cfg.xml");
 SessionFactory sessionFactory = new AnnotationConfiguration().configure(f).buildSessionFactory();

Full Example in, to load “hibernate.cfg.xml” from directory “/conf/“.
package com.tutorialsdesk.hibernate;


import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; 

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();

  private static SessionFactory buildSessionFactory() {
   try {
    //File f = new File("D:\\Workspace\\Kepler\\HibernateExamples\\conf\\hibernate.cfg.xml");
    return new AnnotationConfiguration().configure("/conf/hibernate.cfg.xml").buildSessionFactory(); 
   } catch (Throwable ex) {
    System.err.println("Initial SessionFactory creation failed." + ex);
    throw new ExceptionInInitializerError(ex);

  public static SessionFactory getSessionFactory() {
   return sessionFactory;

  public static void shutdown() {


How to load hibernate.cfg.xml from different directory

Prakash Hari Sharma
I'm a software developer and Java enthusiast. I like clean and modular code, enjoy Agile projects and have a passion for trying out new things. I try to learn and teach every day, and occasionally I'm even able to blog about it. :)