Hibernate: Can multilevel inheritance be mapped to a single table?

I have the following inheritance hierarchy:

Task | SpecificTask | VerySpecificTask 

And I would like it to continue to use unidirectional inheritance, so I annotated the classes:

 @Entity @Table(name="task") @Inheritance(strategy=InheritanceType.SINGLE_TABLE) public class Task @Entity public class SpecificTask extends Task @Entity public class VerySpecificTask extends SpecificTask 

When I try to save an object of the VerySpecificTask class, I get an error message:

 Unable to resolve entity name from Class [com.application.task.VerySpecificTask] expected instance/subclass of [com.application.task.Task] 

How am I wrong? Can multilevel inheritance be matched with a separate table?

EDIT: There was a lame mistake here, I quickly decided, so I deleted it so as not to spoil this question.

+6
source share
3 answers

OK, I added the discriminator column, and now it works. Modified Code:

 @Entity @Table(name="task") @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn( name="DTYPE", discriminatorType=DiscriminatorType.STRING ) @Entity public class SpecificTask extends Task @Entity public class VerySpecificTask extends SpecificTask 

(I am adding it only to provide an acceptable answer - I would not have resolved it without useful comments on the question.)

+4
source

The accepted answer is almost perfect. To make this clearer, I want to add @DiscriminatorValue to each level of inheritance.

 @Entity @Table(name="task") @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn( name="DTYPE", discriminatorType=DiscriminatorType.STRING ) public class Task --- @Entity @DiscriminatorValue(value="DS") public class SpecificTask extends Task --- @Entity @DiscriminatorValue(value="DV") public class VerySpecificTask extends SpecificTask 

And the table with the materials looks like

 --------------- Table: task --------------- |...|DTYPE|...| --------------- |...|DS |...| |...|DV |...| |...|DS |...| ... 
+1
source

Try the @MappedSuperclass annotation:

 @MappedSuperclass public class BaseEntity { @Basic @Temporal(TemporalType.TIMESTAMP) public Date getLastUpdate() { ... } public String getLastUpdater() { ... } ... } @Entity public class Order extends BaseEntity { @Id public Integer getId() { ... } ... } 

In the database, this hierarchy will be presented in the form of an order table with columns id, lastUpdate and lastUpdater. Property mappings of built-in superclasses are copied to subclasses of objects. Remember that an embedded superclass is not the root of a hierarchy.

0
source

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


All Articles