Search code examples
javahibernateinheritancepersistencesingle-table-inheritance

Hibernate: Is it possible to map multi-level inheritance to single table?


I have following inheritance hierarchy:

Task
  |
SpecificTask
  |
VerySpecificTask

And I'd like to persist it usign single-table inheritance, so I annotated 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 VerySpecificTask class, I get an error:

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

What do I wrong? Is it possible to map multi-level inheritance to single table?

EDIT: Here was a lame bug, I've resolved quickly, so I deleted it to not mess this question.


Solution

  • OK, I've added discriminator column and now it works. Changed 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'm adding it just to provide an accepted answer -- I wouldn't resolve it without the helpful comments to the question.)