-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Hibernate Listener Access
PostPosted: Wed May 10, 2006 5:04 am 
Beginner
Beginner

Joined: Thu Apr 20, 2006 11:51 am
Posts: 44
Hibernate version: last
Eclipse: last
jboss: last

Hello
I'm using hibernate with a filter (path /*) that map all the requests.
Now my application is slow because in some jsp I'll use the same selectBox and these are created form DB data with hibernate access.

In my case these selectBox are always the same during the application life, so I'm trying to do a Listener that at the start of my webapp retrives and store these selectBox (an ArrayList) in the ServletContext. In this way I can retrive the box faster.

These are my sources

--- PersistenceFilter ---
Code:
public class PersistenceFilter  implements Filter {

    /**
     * Holds the current hibernate session, if one has been created.
     */
    protected static ThreadLocal hibernateHolder = new ThreadLocal( );
   
    protected static SessionFactory factory;
    //protected static Transaction transaction;
 
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialize hibernate
        try {
            doInit( );
        }
        catch (HibernateException ex) {
            throw new ServletException(ex);
        }     
    }
   
    /**
     * This method should only be called when this class is used directly -
     * that is, when using this class outside of the servlet container.
     * @throws HibernateException
     */
    public static void doInit( ) throws HibernateException {
        factory = new Configuration( ).configure("JNCV.cfg.xml").buildSessionFactory( );
    }

    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
                 throws IOException, ServletException {
        if (hibernateHolder.get( ) != null)
            throw new IllegalStateException(
                "A session is already associated with this thread!  "
                + "Someone must have called getSession( ) outside of the context "
                + "of a servlet request.");
        getSession();
        try { 
            chain.doFilter(request, response);
        }
        finally {
            /*Session sess = (Session)hibernateHolder.get( );
            //transaction.commit();
            if (sess != null) {
               
                hibernateHolder.set(null);
                //transaction=null;
                try {
                    sess.close( );
                }
                catch (HibernateException ex) {
                    throw new ServletException(ex);
                }
            }*/
             HibernateConfigHolder hch = (HibernateConfigHolder)hibernateHolder.get( );
             if(hch!=null){
                 hibernateHolder.set(null);
                 try {
                     hch.getTransaction().commit();
                     hch.getSession().close();
                     hch.setSession(null);
                     hch.setTransaction(null);
                 }
                 catch (HibernateException ex) {
                     throw new ServletException(ex);
                 }
             }
        }
    }
 
    /**
     * ONLY ever call this method from within the context of a servlet request
     * (specifically, one that has been associated with this filter).  If you
     * want a Hibernate session at some other time, call getSessionFactory( )
     * and open/close the session yourself.
     *
     * @return an appropriate Session object
     */
    public static Session getSession( ) throws HibernateException {
       
        /*Session sess = (Session)hibernateHolder.get( );
     
       
        if (sess == null) {
            sess = factory.openSession( );
            hibernateHolder.set(sess);
           
        }*/
        //-----------------------
        HibernateConfigHolder hch = (HibernateConfigHolder)hibernateHolder.get();
        if (hch == null) {
            hch = new HibernateConfigHolder();
            Session sess = factory.openSession();
            Transaction tran = sess.beginTransaction();
            hch.setSession(sess);
            hch.setTransaction(tran);
            hibernateHolder.set(hch);
        }
       
       
        //transaction = sess.beginTransaction();
        return hch.getSession();
    }
 
    /**
     * @return the hibernate session factory
     */
    public static SessionFactory getSessionFactory( ) {
      return factory;
    }
  public static void checkPoint() {
    HibernateConfigHolder hch = (HibernateConfigHolder)hibernateHolder.get();
    if (hch != null) {
      hch.getTransaction().commit();
    }

  }
 
    /**
     * This is a simple method to reduce the amount of code that needs
     * to be written every time hibernate is used.
     */
    public static void rollback(Transaction tx) {
        if (tx != null) {
            try {
                tx.rollback( );
            }
            catch (HibernateException ex) {
                // Probably don't need to do anything - this is likely being
                // called because of another exception, and we don't want to
                // mask it with yet another exception.
            }
        }
    }

    public void destroy( ) {
        // Nothing necessary
    }
   

    public static ThreadLocal getHibernateHolder() {
        return hibernateHolder;
    }
}



--- OQLHelper ---
Code:
public class OQLHelper {

    public static Query createQuery(String query) {
     return PersistenceFilter.getSession().createQuery(query);   
    }

//TODO: da finire recuperare da quella giĆ  fatta

public static void store(Object obj){
     HibernateConfigHolder hch = (HibernateConfigHolder) PersistenceFilter.getHibernateHolder().get( );
     hch.getSession().save(obj);
}
public static void update(Object obj){
     HibernateConfigHolder hch = (HibernateConfigHolder)PersistenceFilter.getHibernateHolder().get( );
     hch.getSession().update(obj);
}
public static void remove(Object obj){
     HibernateConfigHolder hch = (HibernateConfigHolder)PersistenceFilter.getHibernateHolder().get( );
     hch.getSession().delete(obj);
     hch.getSession().flush();
}


}



--- HibernateConfigHolder ---
Code:
public class HibernateConfigHolder {
    private Session session;
    private Transaction transaction;

    public void setSession(Session session) {
        this.session = session;
    }

    public Session getSession() {
        return session;
    }

    public void setTransaction(Transaction transaction) {
        this.transaction = transaction;
    }

    public Transaction getTransaction() {
        return transaction;
    }
}





I try to write a listener that have this contextInitialized method that store the arraylist in the context

Code:
public void contextInitialized(ServletContextEvent event) {
      this.context = event.getServletContext();
      //Output a simple message to the server's console
       System.out.println("=========== The JOBNET Web App. Is Ready ===========");
      
       ArrayList<LabelValueBean> comuni = new ArrayList<LabelValueBean>();
      
      Query queryComuni = OQLHelper.createQuery("from " + ComuniFisc.class.getName());
      List<ComuniFisc> comuniFisc = queryComuni.list();
      for(ComuniFisc comune: comuniFisc) {
         ComuniFiscId cId = (ComuniFiscId) comune.getId();
         comuni.add(new LabelValueBean(cId.getComune()+ " (" + cId.getProv() +")", cId.getCodComune() ));
         //System.out.println("codComune: " + cId.getCodComune() +
          //      "comune" + cId.getComune() + " provincia: " + cId.getProv());
        }
         event.getServletContext().setAttribute(ProjectConstants.SELECTBOX_COMUNI, comuni);
}


but when I try to start the webapp I recive this error


Code:
10:30:20,849 INFO  [STDOUT] =========== The JOBNET Web App. Is Ready ===========
10:30:20,865 ERROR [[/jbn]] Exception sending context initialized event to listener instance of class com.sintesinet.jobnet.cv.listener.SelectBoxListener
java.lang.NullPointerException
   at com.sintesinet.common.persistence.PersistenceFilter.getSession(PersistenceFilter.java:117)
   at com.sintesinet.common.persistence.OQLHelper.createQuery(OQLHelper.java:9)


I think that's because all the hib. mappings have not started yet. or ??
only after this the console shows
Code:
10:30:23,569 INFO  [Configuration] configuring from resource: /hibernate.cfg.xml
10:30:23,569 INFO  [Configuration] Configuration resource: /hibernate.cfg.xml
10:30:23,694 INFO  [Configuration] Mapping resource: common.hbm.xml
10:30:23,819 INFO  [HbmBinder] Mapping class: com.sintesinet.common.ontology.GeneralUser -> GENERALUSER
10:30:24,038 INFO  [HbmBinder] Mapping class: com.sintesinet.common.ontology.AnagraficalData -> ANAGRAFICALDA


etc.



Someone knows what must I change to do that?
thanks a lot guys
bye ;)


Last edited by 6sic6 on Wed May 10, 2006 6:18 am, edited 3 times in total.

Top
 Profile  
 
 Post subject:
PostPosted: Wed May 10, 2006 5:15 am 
Beginner
Beginner

Joined: Thu Apr 20, 2006 11:51 am
Posts: 44
I've modified the listener adding this instructions:
Code:
PersistenceFilter pf = new PersistenceFilter();
pf.doInit();



the listener now appears like.

Code:
public void contextInitialized(ServletContextEvent event) {
      this.context = event.getServletContext();
      //Output a simple message to the server's console
       System.out.println("=========== The JOBNET Web App. Is Ready ===========");
      
       PersistenceFilter pf = new PersistenceFilter();
       pf.doInit();
      
       ArrayList<LabelValueBean> comuni = new ArrayList<LabelValueBean>();
      
      Query queryComuni = OQLHelper.createQuery("from " + ComuniFisc.class.getName());
      List<ComuniFisc> comuniFisc = queryComuni.list();
      for(ComuniFisc comune: comuniFisc) {
         ComuniFiscId cId = (ComuniFiscId) comune.getId();
         comuni.add(new LabelValueBean(cId.getComune()+ " (" + cId.getProv() +")", cId.getCodComune() ));
         //System.out.println("codComune: " + cId.getCodComune() +
          //      "comune" + cId.getComune() + " provincia: " + cId.getProv());
      }
      Collections.sort(comuni);
      event.getServletContext().setAttribute(ProjectConstants.SELECTBOX_COMUNI, comuni);
      
   }


now it works. now my question is..
It's this right for Hibernate pattern?
There's another useful solution?
thanks


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.