Hibernate ManyToMany on the same entity results in recursion

3 weeks ago 16
ARTICLE AD BOX

The Hibernate mapping itself looks fine. The recursion you're seeing is almost certainly happening during JSON serialization (Jackson), not in Hibernate itself. When Jackson serializes a DemoEntity, it serializes friends, which each have friendOf pointing back, which have friends, etc. → infinite loop.

You can break the cycle with @JsonIgnore on one side.

@ManyToMany @JoinTable(name = "friends", joinColumns = @JoinColumn(name = "id1"), inverseJoinColumns = @JoinColumn(name = "id2")) private List<DemoEntity> friends; @JsonIgnore // Don't serialize this side @ManyToMany @JoinTable(name = "friends", joinColumns = @JoinColumn(name = "id2"), inverseJoinColumns = @JoinColumn(name = "id1")) private List<DemoEntity> friendOf;

Murat K.'s user avatar

1 Comment

2026-01-03T13:25:44.173Z+00:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article