0

I work on this project: https://github.com/s1ddok/todosapp

Here you can find all sources for entity etc. What I'm trying to do is to add a connection between TODO and USER. I want that to be a many-to-one relation since one user can have multiple todos, but todos can only have one owner.

I've created a join table in my MySQL database, with foreign keys etc.

Then I added following annotations: enter image description here

enter image description here

And that is raising fatal error on Application start:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain: sample.todosapp.spring.domain.User["todos"]->org.hibernate.collection.internal.PersistentSet[0]->sample.todosapp.spring.domain.Todo["user"]->sample.todosapp.spring.domain.User["todos"]->org.hibernate.collection.internal.PersistentSet[0]->sample.todosapp.spring.domain.Todo["user"]->sample.todosapp.spring.domain.User["todos"]->org.hibernate.collection.internal.PersistentSet[0]->sample.todosapp.spring.domain.Todo["user"]->sample.todosapp.spring.domain.User["todos"]->org.hibernate.collection.internal.PersistentSet[0]->sample.todosapp.spring.domain.Todo["user"]->sample.todosapp.spring.domain.User["todos"]

......

I'm completely lost. I search all related questions and tried all possible annotation variants, but still have no luch. What exactly I did wrong?

Community
  • 1
  • 1
s1ddok
  • 4,615
  • 1
  • 18
  • 31

2 Answers2

0

You should use mappedBy in one of your attributes and not define the relationship in both of them. Remove the annotation @JoinColumn from the HashSet Todo and change @OneToMany(cascade = CascadeType.ALL) to @OneToMany(mappedBy = "user" , cascade = CascadeType.ALL)

Ilona Hari
  • 533
  • 3
  • 14
0

I had the same problem and I tried a different approach. If you need both relationship (@OneToMany and @ManyToOne)in your code (like my case), what should you do?

So you should use @JsonIgnore annotation to break the loop. And the problem was solved. Like it is suggested in this solution

My answer is late, but hope to help someone else!

JTejedor
  • 1,082
  • 10
  • 24