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() {

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

    public void contextDestroyed(ServletContextEvent event) {
        if (emf != null) {


  • Register the listener class in your web.xml
<web-app version="2.5" 
   version="2.5" xmlns="">
  <description>Sample TopLink Application</description>
    <description>Web Application Listener</description>

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