以编程方式配置嵌入式tomcat 7的hibernate [英] configure hibernate with embedded tomcat 7 programmatically

查看:209
本文介绍了以编程方式配置嵌入式tomcat 7的hibernate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经做了一些研究并基于这个长教程更短的一个我提取了以下步骤:
$ b


  1. 创建一个 ServletContextListener

      @WebListener //网上提到的一些文章,将
    // Listener自动添加到应用程序上下文中,但我不相信这适用于我的情况
    public class HibernateListener implements ServletContextListener {
    $ b $ public void contextInitialized(ServletContextEvent event) {
    HibernateUtil.getSessionFactory(); //创建工厂
    }

    public void contextDestroyed(ServletContextEvent event){
    HibernateUtil.getSessionFactory()。close(); //免费资源
    }
    }


  2. 应用程序上下文

     上下文rootCtx = tomcat.addContext(,base.getAbsolutePath()); 
    rootCtx.getServletContext()。addListener(com.example.listeners.HibernateListener);

    tomcat.start();
    tomcat.getServer()。await();


  3. 实现 HibernateUtil 必要的配置

      public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
    try {
    //我应该在返回的配置中调用.configure()吗?
    sessionFactory = getConfiguration()
    .buildSessionFactory();
    } catch(Throwable ex){
    System.err.println(Initial SessionFactory creation failed。+ ex);
    抛出新的ExceptionInInitializerError(ex);



    $ b private static配置getConfiguration(){
    配置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 $
    现在我应该用 MyClass 来通过hibernate创建和从链接的数据库检索数据,对吧? (现在我不确定,究竟如何,但那不是问题)

但不幸的是,当试图添加侦听器到tomcat时, NullPointerException


线程中的异常 mainjava.lang.NullPointerException at
org.apache.catalina.core.ApplicationContext.addListener(ApplicationContext.java:1278)
at
org.apache.catalina.core.ApplicationContextFacade.addListener (ApplicationContextFacade.java:649)

指向 rootCtx.getServletContext()。addListener( com.example.listeners.HibernateListener);



编辑1



但是,如果我正在运行 hibernate standalone (不使用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();
}

所以我配置hibernate的方式很好,我认为。这个错误与听众添加...



我在这里做错了什么?

解决方案

深入挖掘Tomcat的源代码之后,我发现了一个可能的解决方案:

  rootCtx.addApplicationListener(new ApplicationListener(com.example.listeners.HibernateListener,false)); 

它符合我的需求!

I am trying to configure a embedded tomcat instance in my app without any configuration files.

I have done some research and based upon this long tutorial and a shorter one i extracted this steps:

  1. Create a 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
        }
    }
    

  2. Add that Listener to the app context

    Context rootCtx = tomcat.addContext("", base.getAbsolutePath());
    rootCtx.getServletContext().addListener("com.example.listeners.HibernateListener");
    
    tomcat.start();
    tomcat.getServer().await();
    

  3. Implement the HibernateUtil class with the necessary configuration

    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;
        }
    }
    

  4. Now i should somehow work with MyClass 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)

But unfortunately i am getting a NullPointerException when im trying to add the listener to tomcat

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)

which points to the line rootCtx.getServletContext().addListener("com.example.listeners.HibernateListener");

EDIT 1

But if i am running hibernate standalone (without tomcat) it works fine. The Data is being saved without errors!

In 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();
}

So the way i am configuring hibernate is fine i think. The error has something to do with the listener adding...

What am i doing wrong here?

解决方案

After a deep digging in the source code of Tomcat I have found one possible solution:

rootCtx.addApplicationListener(new ApplicationListener("com.example.listeners.HibernateListener", false));

It does what I needed!

这篇关于以编程方式配置嵌入式tomcat 7的hibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆