ClassCastException of entity class

The problem maybe caused by the entity class has been cached in the server even you have renamed the package and redeploy the application. For example, com.service.persistence.delivery.A changed to com.service.persistence.reprint.delivery.A.

private static String persistenceUnitName = "EclipseLinkWeb";
private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);

EntityManagerFactory is acquired statically, and there is no code to free the EntityManagerFactory and other resources before the app starts up again.  This causes the underlying resources to still exist, which have links to the old classloader, and this leads to java.lang.ClassCastException after redeployment.


Workaround:
Please restart the server.

Solution:
First, I added the following method to JPAUtil class:

public class JPAUtil {
  ...
      public static void releaseResources() {
        if (emf != null) {
            emf.close();
        }       
    }
  ...
}


and after that I've created ServletContextListener to release EntityManagerFactory during application shutdown:

public class ShutDownListener implements ServletContextListener {

    public
ShutDownListener () {
    }

    public void contextInitialized(ServletContextEvent arg0) {
    }

    public void contextDestroyed(ServletContextEvent arg0) {
       
JPAUtil.releaseResources();       
    }   
}


Reference:
http://blogs.oracle.com/imc/entry/classcastexception_in_the_eclipselink-based_web_app

留言

這個網誌中的熱門文章

Disable ionic's sidemenu content drag to toggle menu

Multiple writable mappings exist for the field. Only one may be defined as writable, all others must be specified read-only.

java.lang.NoClassDefFoundError: org/apache/xerces/jaxp/datatype/XMLGregorianCalendarImpl$Parser