views:

27

answers:

1

I have a subclass and a superclass. However, only the fields of the superclass are needed to be persist.

session.saveOrUpdate((Superclass) subclass);

If I do the above, I will get the following exception.

org.hibernate.MappingException: Unknown entity: test.Superclass
    at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:628)
    at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1366)
    at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:203)
    at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:535)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:103)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:535)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:527)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:523)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342)
    at $Proxy54.saveOrUpdate(Unknown Source)

How can I persist a subclass as a superclass? I do not prefer creating a superclass instance and then passing the values from the subclass instance. Because, it is easy to forget updating the logic if extra fields are added to superclass in the future.

A: 

What you try to achieve will cause you a lot of problems. Just imagine what happens if you load the data again. Which class is Hibernate supposed to use? The superclass? Or one of the subclasses? Which one?

I suggest to map the superclass directly and then use the delegate pattern to implement the extended functionality (basically turning your superclass in a data object which gets passed to "worker" instances).

Aaron Digulla
I will only load the data to superclass only.Your suggestion also requires notifying a update of the delegation if the superclass adds extra fields.
franziga