inheritancecachingeclipselinkjpa-2.0

JPA [EcliseLink]: Cannot change the type of an instance of parent A to subclass B In the single table inheritance


I use Eclipselink-2.6 with wildfly-8 server in a JavaEE7 application.

I have three JPA entities A, B, and C.

B and C extend A.

I need to change the type of an entity instance myObjectId A to B, persisting the same id.

I tried to do the following in the same transaction scope:

1- Change the dtype value from "a" to "b" for the instance "myObjectId".

2- save A, flush, then clear cache, using evict, and using ((JpaEntityManager)em.getDelegate()).getServerSession().getIdentityMapAccessor().initializeAllIdentityMaps().

3- find by id the new object by the class b em.find(B.class, oldId);

This results in a class cast exception, cannot Cast Class A to B!

Any help would to understand this behavior, and to find a solution would be appreciated.


Solution

  • This is what worked for me:

    I edited the dtype of instant myObjectId from A to B, and merged it; Detached the entity myObjectId.

    Clears the cache of em using: ((JpaEntityManager)em.getDelegate()).getServerSession().getIdentityMapAccessor().initializeAllIdentityMaps() Find the entity of type B of id myObjectId.id;

    oldId = myObjectId.getId();
    myObjectId.setdType("a");
    em.merge(myObjectId);
    em.flush();
    em.detach(myObjectId);
    

    Then, get the new Object b:

    ((JpaEntityManager)em.getDelegate()).getServerSession().getIdentityMapAccessor().initializeAllIdentityMaps();
    B newEntity = em.find(B.class, oldId);
    // Edited B as filling its fields...
    newEntity = em.merge(newEntity);