1

I have the following inheritance chain:

@MappedSuperclass
public abstract class AbstractEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    Long id;
}

@Entity
@Table(name = "answers")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Answer extends AbstractEntity {

}

@Entity
@Table(name = "chosen_answers")
@PrimaryKeyJoinColumn
public class ChosenAnswer extends Answer {

    @ManyToOne(optional = false)
    @NotNull
    AnswerChoice answerChoice;

}

@Entity
@Table(name = "free_text_answers")
@PrimaryKeyJoinColumn
public class FreeTextAnswer extends Answer {

    String answerText;

}

The (simplified) sample content of my database looks like this:

answers:

--ID---

| 100 |

free_text_answers:

--ID----answer_text--

| 100 | "Some text" |

The foreignkey from free_text_answers(id) to answers(id) is created. The problem is that the entity manager returns null for the following statement:

em.find(Answer.class, 100l); // returns null

although, 100 is a valid id for a stored answer. If I query the entity manager for instances of FreeTextAnswer, I get the expected result.

em.find(FreeTextAnswer.class, 100l) // returns stored entity

The strange thing is, as soon as I query the entity manager for the subtype, the first statement also returns the requested entity.

Is this the expected result? If yes, how do I design my inheritance chain to work the way I like?

I am using Spring Data Rest, and I only expose the Answer-entity via a RestRepository, therefore Spring Data Rest calls the entity manager with an Answer as the expected entity.

Thomas Eizinger
  • 1,404
  • 14
  • 25

1 Answers1

1

After some further debugging with the generated SQL statements, I found a workaround to solve the problem.

As you can see in the ER diagram below, one subclass of Answer has a OneToOne relationship to another entity. The default fetchtype for such a relationship is EAGER which turned out to be the problem. As soon as I configured hibernate to lazy-load this relationship, everything works as expected.

Is this a bug in hibernate?

ER Diagram

Thomas Eizinger
  • 1,404
  • 14
  • 25