title: configure hibernate with embedded tomcat 7 programmatically
body: <p>I am trying to configure a embedded tomcat instance in my app without any configuration files.</p>
  
  <p>I have done some research and based upon this <a href="http://www.ehow.com/how_7999843_stepbystep-hibernate-tomcat-mysql-tutorial.html" rel="nofollow">long tutorial</a> and <a href="https://community.jboss.org/wiki/UsingHibernateWithTomcat" rel="nofollow">a shorter one</a> i extracted this steps:</p>
  
  <ol>
  <li><p>Create a <code>ServletContextListener</code></p>
  
  <pre><code>@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
      }
  }
  </code></pre></li>
  <li><p>Add that Listener to the app context</p>
  
  <pre><code>Context rootCtx = tomcat.addContext("", base.getAbsolutePath());
  rootCtx.getServletContext().addListener("com.example.listeners.HibernateListener");
  
  tomcat.start();
  tomcat.getServer().await();
  </code></pre></li>
  <li><p>Implement the <code>HibernateUtil</code> class with the necessary configuration</p>
  
  <pre><code>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;
      }
  }
  </code></pre></li>
  <li><p>Now i should somehow work with <code>MyClass</code> to create and retrieve data from the linked database through hibernate, right? (right now i am not sure, how exactly, but thats not the point here)</p></li>
  </ol>
  
  <p>But unfortunately i am getting a <code>NullPointerException</code> when im trying to add the listener to tomcat</p>
  
  <blockquote>
    <p>Exception in thread "main" java.lang.NullPointerException     at
    org.apache.catalina.core.ApplicationContext.addListener(ApplicationContext.java:1278)
      at
    org.apache.catalina.core.ApplicationContextFacade.addListener(ApplicationContextFacade.java:649)</p>
  </blockquote>
  
  <p>which points to the line <code>rootCtx.getServletContext().addListener("com.example.listeners.HibernateListener");</code></p>
  
  <p><strong>EDIT 1</strong></p>
  
  <p>But if i am running <strong>hibernate standalone</strong> (without tomcat) it works <strong>fine</strong>. The Data is being saved without errors!</p>
  
  <p>In <code>HibernateUtil</code></p>
  
  <pre><code>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();
  }
  </code></pre>
  
  <p>So the way i am configuring hibernate is fine i think. The error has something to do with the listener adding...</p>
  
  <p>What am i doing wrong here?</p>