How to load hibernate.cfg.xml from different directory

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 :


Initial SessionFactory creation failed.org.hibernate.HibernateException: 
/hibernate.cfg.xml not found

Exception in thread "main" java.lang.ExceptionInInitializerError
	at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:25)
	at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8)
	at com.mkyong.common.App.main(App.java:11)
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
	at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
	at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
	at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
	at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
	at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
	... 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 Configuration()
            .configure("/com/mkyong/persistence/hibernate.cfg.xml")
            .buildSessionFactory();
            
            return sessionFactory;

HibernateUtil.java

Full Example in HibernateUtil.java, to load “hibernate.cfg.xml” from directory “/com/mkyong/persistence/“.


import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// load from different directory
			SessionFactory sessionFactory = new Configuration().configure(
					"/com/mkyong/persistence/hibernate.cfg.xml")
					.buildSessionFactory();

			return sessionFactory;

		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void shutdown() {
		// Close caches and connection pools
		getSessionFactory().close();
	}

}

Done.

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

20 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
PhanVu HoaiNam
10 years ago

Thank you. It’s helpful.

Luciano Seibel
10 years ago

Can I change the configuration set in .xml on login time? For change de user and pass for another who has the real database access…

The Hien Pham
11 years ago

Thanks for this post!

I have a question. Can I execute a hibernate project in another?

When I call a method in hibernate project in another, it throw an exception:

java.lang.NoSuchMethodError: org.hibernate.SessionFactory.getCurrentSession()Lorg/hibernate/Session;

Can you help me, please?

Thank you very much!

rahul jain
10 years ago
Reply to  The Hien Pham

assxs

Davies Arthur M.
11 years ago

to load hibernate.cfg.xml from a different directory use the configure(File configFile) method that takes the hibernateConfig File argument.
(note, am using hibernate 4.3.7)

Like this:

—-

String hibernatePropsFilePath = “/com/mkyong/persistence/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);

—–

Jeff
11 years ago

new Configuration()
.configure(“/com/mkyong/persistence/hibernate.cfg.xml”)
.buildSessionFactory()

is deprecated

Nishant Mishra
12 years ago

what if my file is not in root directory and still i am using configure(“hibernate.cfg.xml”) and have

/com/mkyong/persistence/ in my classpath. will it than refer the file. i have problems
refering the same.

Erez
13 years ago

Beautiful! Thanks!

B?ch
13 years ago

This code not working
Error: /com/mkyong/persistence/hibernate.cfg.xml not found

SyedThayeefAhmed
13 years ago
Reply to  B?ch

set the path of the configuration file

Walker Rowe
13 years ago

Mykong thanks again. Your web site is filled with useful information.

Carlos Gonzaga
13 years ago

\o/ wowwwwww thanks!!

Vishal Panchal
13 years ago

It works like charm..
Thanks..!

Mufim
13 years ago

Very Good ANSWER

Abraham
14 years ago

I got the error, Message table not found.
Do I have to manually create it on my MySql database. If so, what is the command to do it?

Thanks in advance

rakesh b.k
9 years ago

can this method be used with struts 1 ?

Mahesh
14 years ago

I have my hibernate.cfg.xml file in project root folder(src). But flowing errors are in NetBeans IDE
INFO: configuring from resource: /hibernate.cfg.xml
Feb 27, 2012 8:51:35 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Exception in thread “main” org.hibernate.HibernateException: /hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
at com.hibernate.hibr.main(hibr.java:18)

Shams
15 years ago

Thanks for this post.

Really helpful
Thanks again

emogirl
15 years ago

thank you so much im dying fuck everything

Rakesh
7 years ago
Reply to  emogirl

which component load the hibenate.cfg.xml file in hibernate?