Hibernate inheritance and polymorphism
<p>I have a class hierarchy that i've mapped to a database with Hibernate using the single table per class hierarchy strategy.</p>

<p>Here is the UML of my class Hierarchy</p>

<p><a href="https://i.stack.imgur.com/NjAs9.jpg" rel="nofollow">class hierarchy UML diagram</a></p>

<p>The Hibernate mapping is as follows</p>

<pre><code>@Entity
@Table(name = "FRUIT_HIERARCHY")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "discriminator", discriminatorType = DiscriminatorType.STRING)
public abstract class Fruit{

         @Id
         @Column(name = "id_registred_user")
         private long id;
}

@DiscriminatorValue(value = "Banana")
public class Banana extends Fruit{}

@DiscriminatorValue(value = "Orange")
public class Orange extends Fruit{

        @OneToMany(mappedBy = "orange", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
        private List&lt;Note&gt; noteList;
}
</code></pre>

<p>Here is the details concerning my Postgresql database</p>

<p><a href="https://i.stack.imgur.com/r8JpA.jpg" rel="nofollow">database schema</a></p>

<p>Here is the database</p>

<pre><code>create table FRUIT_HIERARCHY (
        ID_FRUIT             SERIAL               not null,
        DISCRIMINATOR        VARCHAR(50)          null,
        constraint PK_FRUIT_HIERARCHY primary key (ID_FRUIT)
);

create table NOTE (
        ID_NOTE              SERIAL               not null,
        ID_FRUIT             INT4                 not null,
        constraint PK_NOTE primary key (ID_NOTE)
);

alter table NOTE
   add constraint FK_NOTE_FRUIT foreign key (ID_FRUIT)
   references FRUIT_HIERARCHY (ID_FRUIT)
   on delete restrict on update restrict;
</code></pre>

<p>The problem comes when i have to implement the hibernate association between Orange class and Note. An Orange has 0 to n Notes and a Note belong to one Orange. And Orange is a subclass of Fruit.</p>

<pre><code>@Entity
@Table(name = NOTE)
public class Note{

      @Id
      @Column(name = "id_note")
      private long id;

      @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
      @JoinColumn(name = "id_fruit")
      private Orange orange
}
</code></pre>

<p>Is the this Hibernate association mapping correct knowing that Orange is a subclass of Fruit? Will hibernate retrieve an Orange object from the table FRUIT_HIERARCHY? should i map it by putting a Fruit attribute and using casting when it comes to use an Orange object?</p>

<p>Thank you.</p>