Mapped subclass is retrieved as superclass by Hibernate

209 Views Asked by At

I have a class Project, a superclass Resource with two subclasses StorageResource and ComputeResource. I have defined a Hibernate mapping (I am using Hibernate version 5.3.7.Final) as follows:

    @Entity
    @Table(name = "PROJECTS", ...})
    public class Project implements Serializable {
        ...
        @OneToMany(
            mappedBy = "project",
            cascade = CascadeType.ALL,
            orphanRemoval = true
        )
        private List<Resource> resources;
        ...
    }


    @Entity
    @Table(name = "resources")
    @Inheritance(strategy = InheritanceType.JOINED)
    public class Resource implements Serializable {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        private long id;

        @ManyToOne
        private Project project;
        ...
    }

    @Entity
    @Table(name = "storage_resources")
    @PrimaryKeyJoinColumn(name = "id")
    public class StorageResource extends Resource implements Serializable {
        ...
    }

    @Entity
    @Table(name = "compute_resources")
    @PrimaryKeyJoinColumn(name = "id")
    public class ComputeResource extends Resource implements Serializable {
        ...
    }

My Java code can save instances of both subclasses (StorageResource and ComputeResource) correctly to the database. However, when I load these records by loading a project and its resources, I have the following:

  • Storage resource records are loaded as Java objects that are instances of StorageResource,
  • Compute resource records are loaded as Java objects that are instances of Resource, not of ComputeResource as I would expect.

I have spent the last two days trying to figure out why this is happening: the mappings of both sub-classes are the same. Am I missing something?

EDIT

I found the problem. It was quite misleading, because there was no error message. The environment in which the bug occurred had an outdated configuration file. The Hibernate mapping for ComputeResource

<mapping class="....ComputeResource"/>

was missing. After adding this line the mapping is working as expected.

0

There are 0 best solutions below