I have a project with Spring Boot, and I cannot make lazy loading work. I have 2 entities: Question
and Answer
. A question can have many answers.
What I want is, when I try to get an answer, to get only the answer without the question. And also, if I want both, to have this possibility.
What I did, is I added in application.yml: spring.jpa.open-in-view: true.
The Answer
entity is like:
@Entity
@Table(name = "mst_ans_answer", schema = "lquest_sc")
public class Answer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "lquest_sc.mst_ans_answer_ans_lqs_id_seq")
@SequenceGenerator( name = "lquest_sc.mst_ans_answer_ans_lqs_id_seq", sequenceName = "lquest_sc.mst_ans_answer_ans_lqs_id_seq")
@Column(name = "ans_lqs_id")
private int id;
@Column(name = "qst_lqs_id")
private int questionId;
@Column(name = "ans_text")
private String text;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "qst_lqs_id", insertable=false, updatable=false)
@JsonIgnore
private Question question;
//getters and setters
}
The Question
entity is:
@Entity
@Table(name = "mst_qst_question", schema = "lquest_sc")
public class Question implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "lquest_sc.mst_qst_question_qst_lqs_id_seq")
@SequenceGenerator(name = "lquest_sc.mst_qst_question_qst_lqs_id_seq", sequenceName = "lquest_sc.mst_qst_question_qst_lqs_id_seq")
@Column(name = "qst_lqs_id")
private int id;
@Column(name = "qst_title")
private String title;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "question")
@OrderBy("order asc")
private Set<Answer> answers = new HashSet<Answer>();
//getters and setters here
The call in the controller is:
@RequestMapping(value = "/questionId/{id}", method = RequestMethod.GET)
public List<Answer> listAll( @PathVariable("id") int id ){
List<Answer> answers = answerRepository.findByEnabledAndQuestionIdOrderByOrderAsc(1,id);
return answers;
}
and the repository is
public interface AnswerRepository extends JpaRepository<Answer, Long> {
List<Answer> findByEnabledAndQuestionIdOrderByOrderAsc(int enabled,int questionId);
}
The problem is that in the controller, when I try to evaluate
answers.get(0).getQuestion()
, I receive the entity of Question, with the properties filled with null
values and the error Method threw 'org.hibernate.LazyInitializationException' exception. Cannot evaluate Question_$$_jvst5b6_1.toString()
. What am I doing wrong?