Persistent subclass as a superclass using Hibernate

I have a subclass and a superclass. However, you need to save only the fields of the superclass.

session.saveOrUpdate((Superclass) subclass);

If I do this, 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 save a subclass as a superclass? I do not prefer to instantiate a superclass and then pass values ​​from an instance of the subclass. Because it is easy to forget to update the logic if additional fields are added to the superclass in the future.

+3
source share
3 answers

There is a certain type of solution to this problem, and it is really addressed here at StackOverFlow:

Hibernate / NHibernate: how to save a subclass as an instance of a superclass

Hibernate documentation

, Hibernate, , , :

session.save( "my.superclass", );

, .

+2

, , . , , . Hibernate? ? ? ?

, ( "" ).

+1

, . . , User, . , , , , .., .

, , " ", / , " " ", . , User, , User. - , .

, , - User, EditableUser, , "changePassword" "confirmPassword", . , Hibernate , EditableUser. ( EditableUser , , , )

The way I came across this problem is to use delegation: create an EditableUser object that has a user inside it, as well as additional properties that I don't want to save. This works quite well, except that it means that all my data bindings to the form must be changed to access the internal user object, so it feels pretty dirty.

0
source

Source: https://habr.com/ru/post/1750459/


All Articles