I have been working on a project and trying to perform a DTO projection for my base class but I have an issue.
Here's my entities:
@Entity
@Table(name = "QUESTION")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("DESCRIPTIVE")
public class Question extends BaseEntity<Long> {
@Column(name = "TITLE",
nullable = false)
private String title;
@Column(name = "QUESTION_BODY",
nullable = false)
private String questionBody;
@Column(name = "QUESTION_TYPE",
nullable = false)
private QuestionType questionType;
}
And TestQuestion entity which extends base Question Entity:
@Entity
@DiscriminatorValue("TEST")
public class TestQuestion extends Question {
@OneToMany(mappedBy = "testQuestion",
cascade = CascadeType.ALL,
orphanRemoval = true)
private Set<Option> options;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "RIGHT_OPTION_ID")
private Option rightOption;
}
Now I have a base Question repository extending the JpaRepository which has the findAll method:
public interface QuestionRepository extends JpaRepository<Question, Long> {
@Query("select tq from Test t join t.questions tq where t.id = :testId ")
List<Question> fetchTestQuestions(Long testId);
}
When I fetch all the questions, since I have a rest api and the question entity has all the other attributes with toMany relationships, I get a recursive JSON which is a mess! I tried to use @JsonIgnore but it didn't work so I decided to use DTO projection.
The problem is I dont know how to perform a dto projection to call the constructor of each of my DTOs like QuestionDTO and TestQuestionDTO for each of the Questions since each of them have their own types.
Is such a thing even possible?