Saturday, January 21, 2017

TopLink - Common Errors - ClassCastException

Are you facing a class cast exception while using Oracle TopLink?
For example - com.entity.Organization cannot be cast to com.entity.Organization

In my experience, this issue occurred sporadically and was not consistent. The reason this occurs is because multiple instances of Entity Manager have been created in your application session. The class loader is hence unable to determine the instance of the class that is to be loaded

Here is how I was able to workaround the issue:

  • Create a listener class (myListner) as shown below
    • Override the contextInitialized method to create an entity manager as soon as the application session is initiated
    • Override the contextDestroyed method to release the entity manager as soon as the application session ends
  • This will ensure only a single instance of entity manager exists at any point in time. Thus, eliminating the root cause.


package com.db.dao;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class myListener implements ServletContextListener {
    private static String persistenceUnitName = "Persistent_Unit_Name";
    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);

    public myListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        if (!emf.isOpen()) {
            emf = Persistence.createEntityManagerFactory(persistenceUnitName);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        if (emf != null) {
            emf.close();
        }
    }

}

  • Register the listener class in your web.xml
<web-app version="2.5" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
  <display-name>myTopLinkProject</display-name>
  <description>Sample TopLink Application</description>
  <filter>
    <filter-name>JpsFilter</filter-name>
    <filter-class>oracle.security.jps.ee.http.JpsFilter</filter-class>
    <init-param>
      <param-name>enable.anonymous</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>JpsFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
  </filter-mapping>
  <listener>
    <description>Web Application Listener</description>
    <display-name>myListener</display-name>
    <listener-class>ul.iam.db.dao.myListener</listener-class>
  </listener>
</web-app>





Hope you find this helpful! Please share your feedback below.

CaptiveCode


No comments:

Post a Comment