我正在尝试在我的应用程序中配置一个嵌入式 tomcat 实例,而无需任何配置文件。
我已经做了一些研究,并基于这个长教程和一个较短的教程,我提取了以下步骤:
创建一个
ServletContextListener
@WebListener //some articles on the web mentioned, that this would add the //Listener automatically to the app context, but i cant believe that this works in my case public class HibernateListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { HibernateUtil.getSessionFactory(); // create a factory } public void contextDestroyed(ServletContextEvent event) { HibernateUtil.getSessionFactory().close(); // free resources } }
将该侦听器添加到应用程序上下文
Context rootCtx = tomcat.addContext("", base.getAbsolutePath()); rootCtx.getServletContext().addListener("com.example.listeners.HibernateListener"); tomcat.start(); tomcat.getServer().await();
HibernateUtil
使用必要的配置实现类public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { //should i call .configure() on the returned Configuration here? sessionFactory = getConfiguration() .buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } private static Configuration getConfiguration(){ Configuration c = new Configuration(); c.setProperty("hibernate.connection.url", "jdbc:hsqldb:hsql://localhost:1234/mydb1"); c.setProperty("hibernate.connection.username", "SA"); c.setProperty("hibernate.connection.password", ""); c.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver"); c.setProperty("dialect", "org.hibernate.dialect.HSQLDialect"); c.setProperty("cache.provider_class", "org.hibernate.cache.NoCacheProvider"); c.setProperty("cache.use_query_cache", "false"); c.setProperty("cache.use_minimal_puts", "false"); c.setProperty("max_fetch_depth", "3"); c.setProperty("show_sql", "true"); c.setProperty("format_sql", "true"); c.setProperty("hbm2ddl.auto", "create"); c.addPackage("com.example.models"); c.addAnnotatedClass(MyClass.class); return c; } public static SessionFactory getSessionFactory() { return sessionFactory; } }
现在我应该以某种方式
MyClass
通过休眠从链接数据库中创建和检索数据,对吗?(现在我不确定,具体如何,但这不是重点)
但不幸的是,NullPointerException
当我尝试将侦听器添加到 tomcat 时,我得到了一个
org.apache.catalina.core.ApplicationContextFacade.addListener(ApplicationContextFacade.java:649) 的 org.apache.catalina.core.ApplicationContext.addListener(ApplicationContext.java:1278) 的线程“main”java.lang.NullPointerException 中的异常
指向线rootCtx.getServletContext().addListener("com.example.listeners.HibernateListener");
编辑 1
但是如果我独立运行休眠(没有tomcat)它工作正常。数据保存无误!
在HibernateUtil
public static void main(String[] args) {
MyClass mycls = new MyClass();
mycls.setMyProperty("My Property");
Session session = getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.save(mycls);
transaction.commit();
}
所以我认为我配置休眠的方式很好。该错误与添加的侦听器有关...
我在这里做错了什么?