SessionFactory creation failed.java.lang.NoClassDefFoundError

While practicing the Hibernate auto increment example, I have faced lots of issues. In that one of the thing is SessionFactory creation error. Error stack trace is as follows,

SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Exception in thread "main" java.lang.ExceptionInInitializerError
       at com.jtb.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
       at com.jtb.util.HibernateUtil.<clinit>(HibernateUtil.java:8)
       at com.jtb.test.DeleteUser.main(DeleteUser.java:11)


Caused by: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
       at org.hibernate.cfg.AnnotationConfiguration.<clinit>(AnnotationConfiguration.java:65)
       at com.jtb.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:12)
       ... 2 more
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
       at java.net.URLClassLoader$1.run(Unknown Source)
       at java.net.URLClassLoader$1.run(Unknown Source)
       at java.security.AccessController.doPrivileged(Native Method)
       at java.net.URLClassLoader.findClass(Unknown Source)
       at java.lang.ClassLoader.loadClass(Unknown Source)
       at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
       at java.lang.ClassLoader.loadClass(Unknown Source)
       ... 4 more

Here is the HibernateUtil class which I have tried creating the SessionFactory instance.
package com.jtb.util;

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

public class HibernateUtil {

 private static SessionFactory sessionFactory = null;

 private static synchronized SessionFactory buildSessionFactory() {
  try {
   return new AnnotationConfiguration().buildSessionFactory();
  } catch (Throwable ex) {
   System.err.println("SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }

 public static SessionFactory getSessionFactory() {
  return buildSessionFactory();
 }

 public static void shutdown() {
  getSessionFactory().close();
 }

}

Solution:
To solve the problem, you need to include the commons-logging.jar file into your project classpath or add the dependency to your pom.xml if you are using maven.
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

Add the below lines into your build.gradle if you are Gradle build tool.
// https://mvnrepository.com/artifact/commons-logging/commons-logging
compile group: 'commons-logging', name: 'commons-logging', version: '1.2'


Popular posts from this blog

how to count the page views by using JSP

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Multithreading in java with example