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

  myTopLinkProject
  Sample TopLink Application
  
    JpsFilter
    oracle.security.jps.ee.http.JpsFilter
    
      enable.anonymous
      true
    
  
  
    JpsFilter
    /*
    FORWARD
    REQUEST
    INCLUDE
  
  
    Web Application Listener
    myListener
    ul.iam.db.dao.myListener
  






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

CaptiveCode