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.