网络上有一个示例,说明如何在Hibernate中使用批注(在我处理同一个示例之前,但它使用了.xml。而且我设法使其无例外地工作)。
所以现在我有:

Initial session factory creation failedjava.lang.NoSuchFieldError: namingStrategy
Exception in thread "main" java.lang.ExceptionInInitializerError
at firstproject.HibernateUtil.<clinit>(HibernateUtil.java:14)
at firstproject.StudentDAO.addSubject(StudentDAO.java:82)
at firstproject.Test.main(Test.java:12) Caused by: java.lang.NoSuchFieldError: namingStrategy
at org.hibernate.cfg.AnnotationConfiguration.reset(AnnotationConfiguration.java:250)
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:108)
at firstproject.HibernateUtil.<clinit>(HibernateUtil.java:11)
... 2 more


这是一些代码,可能会有所帮助:

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); // HibernateUtil.java:11
        } catch (Throwable ex) {
            System.err.println("Initial session factory creation failed" + ex);
            throw new ExceptionInInitializerError(ex); // HibernateUtil.java:14
        }
    }

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

public class StudentDAO {
    public Long addSubject(Subject subject) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession(); // StudentDAO.java:82
        session.beginTransaction();
        Long result = (Long) session.save(subject);
        session.getTransaction().commit();
        return result;
    }
}

public class Test {
    public static void main(String[] args) {
        StudentDAO dao = new StudentDAO();
        Subject subject = new Subject();
        subject.setSubjectName("Mathematics");
        dao.addSubject(subject); // Test.java:12
    }
}

最佳答案

嗨克莱欧

您已在HibernateUtil类中编写了以下行。

sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();


用下面编写的行替换此代码行,然后重试。希望这对您有用。

sessionFactory = new Configuration().configure().buildSessionFactory();

10-04 10:15