Issue
Apologies for abusing the format, I'm not really asking a question here but I sure wish this would have shown up when I started banging my head against this wall two weeks ago.
I've inherited several large Java projects, using Spring and running on Tomcat, and am upgrading the frameworks used by them. However, when I upgrade Hibernate I suddenly get ExceptionInInitializer: root cause UnknownEntityException. Our HibernateConf looks like so:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
}
We're still using hbm.xml to describe mappings, they are placed in individual files and included in hibernate.cfg.xml.
Solution
Now that I have finally got it to work again, here is what I've learned: Apparently, the boot context is unable to locate hibernate.cfg.xml, but fails silently. Inside HibernateUtil, I can use addResource and addAnnotatedClass because they use Java's class loader, so I need to list every HBM file and entity class before creating the session factory. Like so:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
configuration.addResource("path/to/my/mapping.hbm.xml");
configuration.addAnnotatedClass(my.package.for.Persistence.class);
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
}
And now it works. The reason is that most file lookups are done relative to TomCat's working directory, but a select few use ClassLoader and can therefore more easily find resource files in the source tree.
Answered By - Zaleth
Answer Checked By - Cary Denson (JavaFixing Admin)