0

I probably misunderstood some basics of JPA. I got a kind of circular reference on objects returned...

I had a list of questions, each with a list of responses. But with the JPA mapping i did, each response also have a question. See here :

@Entity
public class Question implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // A question has several responses
    @OneToMany(mappedBy = "question", fetch = FetchType.EAGER)
    private List<Reponse> reponses;

@Entity
public class Reponse implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;

    // This is here to specify the join column key "question_id"
    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

As you see here, I have a question[0] which has a list of responses, but each has a question, which also have a list of responses and so on... :

enter image description here

How can i specify the join column key without having to bring the whole object and all his children and so on ?

Thank you very much for your help !

Joss

jozinho22
  • 185
  • 15
  • You need to use lazy loading https://stackoverflow.com/questions/2192242/what-is-lazy-loading-in-hibernate – ntholi May 22 '20 at 15:38

2 Answers2

1

In the configuration you did the flow retrieves data in following order:

  • Question object
  • Related entities (namely Response objects) due to the FetchType.EAGER
  • Questionobject again
  • repeat all steps

This is since in "to one" association the fetch = FetchType.EAGER is used by default.

Lazy loading is then the answer, you have to set FetchType.LAZY in Response object over the question field as @ManyToOne(fetch = FetchType.LAZY) in order to stop the cycle.

DiegLuthor
  • 175
  • 10
0

Update the question to FetchType.LAZY

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "question_id")
private Question question;
sc0der
  • 4,152
  • 2
  • 12
  • 24