users@glassfish.java.net

Closing EMF during web app reload/restart (was Re: Same app twice using JPA)

From: Edson Carlos Ericksson Richter <edson.richter_at_mgrinformatica.com.br>
Date: Thu, 12 Jul 2007 11:40:35 -0300

Hi, I just wanna share with other guys the code for closing the EMF
during web app restart (either module reload or web server restart):

/** A ServletContextListener that close EntityManagerFactory when server
reload/restart a web app
  * @Author: Edson Carlos Ericksson Richter
  * License: use as you want, change as you need.
  * If you like, send me a picture of the nature from any place around
the world.
  */
public class SessionManager implements ServletContextListener {
 
  /** Creates a new instance of SessionManager */
  public SessionManager() {
  }

  public void contextInitialized(ServletContextEvent servletContextEvent) {
    System.out.println("Web app initialized - chage this message to be
more informative as you need.");
  }

  public void contextDestroyed(ServletContextEvent servletContextEvent) {
    System.out.println("Closing EntityManagerFactory for releasing
resources (and caches?!).");
    // put your emf.close command here. In my case, all EMF
    // related operations are on DataUtil class (pattern Utility), so I
just do DataUtil.reset();
    System.out.println("EntityManagerFactory closed with success.");
  }
}


Don't forget to put in web.xml the following:


    <listener>
        
<listener-class>the.paccage.of.your.clazz.SessionManager</listener-class>
    </listener>

just before any other <servlet> declaration...

Thank you very much, Sahoo - your directions solved another problem on
my server (several ClassCastException after web app reloads!!!). This
speeds a lot web development, as never needed to restart app server
again during deploy/fix/redeploy cicle.


Regards,

Edson Carlos Ericksson Richter



Sahoo escreveu:
> Yes, TopLink is definitely mixing things up. See issue 3235 [1] where
> this exact problem is discussed recently. As you pointed out, closing
> the emf during undeployment won;t avoid the class linking issue. I was
> thinking that you actually deploy the same app (with same war/ear
> name) twice.
>
> In any case, you should add the code that closes the emf - that makes
> it a better app.
>
> Thanks,
> Sahoo
>
> [1] https://glassfish.dev.java.net/issues/show_bug.cgi?id=3235