SessionFactory creation failed.java.lang.NoSuchFieldError: namingStrategy

While creating the SessionFactory in Hibernate I have faced lot's of issues. This is also one the exception which I have faced,

SessionFactory creation failed.java.lang.NoSuchFieldError: namingStrategy
Exception in thread "main" java.lang.ExceptionInInitializerError
       at com.jtb.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
       at com.jtb.util.HibernateUtil.getSessionFactory(HibernateUtil.java:18)
       at com.jtb.test.DeleteUser.main(DeleteUser.java:11)
Caused by: java.lang.NoSuchFieldError: namingStrategy
       at org.hibernate.cfg.AnnotationConfiguration.reset(AnnotationConfiguration.java:237)
       at org.hibernate.cfg.Configuration.<init>(Configuration.java:125)
       at org.hibernate.cfg.Configuration.<init>(Configuration.java:119)
       at org.hibernate.cfg.AnnotationConfiguration.<init>(AnnotationConfiguration.java:96)
       at com.jtb.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:10)
       ... 2 more

Here is the HibernateUtil class which I have placed the SessionFactory creation logic into it. Since, I am using Annotations, I have tried creating the SessionFactory by using AnnotationConfiguration.
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:
The mistake what I have done is, I have used AnnotationConfiguration() to create the SessoinFactory instance. If we are using annotations also, it is fine to use Configuration() only.

Replace the below line
return new AnnotationConfiguration().buildSessionFactory();

with
return new Configuration().configure().buildSessionFactory();

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