Search code examples
javahibernatenhibernate-mapping

Getting hibernate entity name from the object


Is there any way to figure out what entity name the loaded by hibernate object has? I have one class that is mapped to 2 different tables (someone thought that it is a good idea):

class MyEntity {
  <some fields>
}

<hibernate-mapping>
   <class name="MyEntity" table="MyEntity" entity-name="MyEntity">
     ...
   </class>
   <class name="MyEntity" table="MyEntityOld" entity-name="MyEntityOld">
      ...
   </class>
</hibernate-mapping>

to get corresponding instance:

res = getSession().createCriteria("MyEntity")
if (res == null) {
  res = getSession().createCriteria("MyEntityOld")
}

return res;

This works fine, the problem is I don't want to refactor hundred of places just to pass everywhere how that entity was received. Moreover there a lot of inherited subclasses from MyEntity as well as MyEntityOld (like mirroring of real classes to its "OLD" doppelgängers). So is there any way to get the entity name with having just the object

PS: object.getClass() obviously won't work since for the class there is a real "MyEntity"


Solution

  • I think this is a good solution to your problem.

    Hibernate get entity name value

    Having MyEntity as a base class and having a MyEntityNew and MyEntityOld extend MyEntity, will allow you differentiate between the two objects, on a per need bases.

    <hibernate-mapping>
       <class name="MyEntityNew" table="MyEntity" entity-name="MyEntityNew">
         ...
       </class>
       <class name="MyEntityOld" table="MyEntityOld" entity-name="MyEntityOld">
          ...
       </class>
    </hibernate-mapping>
    

    You may also need to set up a @MappedSuperclass annotation for MyEntity aswell.