0

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"

Mike
  • 28
  • 5

1 Answers1

1

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.

avalerio
  • 2,072
  • 1
  • 12
  • 11
  • Yeah, it should work. Thank you. Nonetheless, I decided to go a slightly different way. I've added a Transient field in the MyEntitiy. This field is set to false for the regular table and true for the "Old" table". I fill it up with a tuplizer – Mike Jun 28 '21 at 15:51