I am working on a Java application using Spring Boot, and I have a UserEntity
class where users can follow each other. However, when two users follow each other, I encounter a java.lang.StackOverflowError
. Here is my current UserEntity
class:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "user")
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userName;
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_followings",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "following_id")
)
@JsonIgnoreProperties({"followers", "followings"})
@Builder.Default
private Set<UserEntity> followings = new HashSet<>();
@ManyToMany(mappedBy = "followings", fetch = FetchType.EAGER)
@JsonIgnoreProperties({"followers", "followings"})
@Builder.Default
private Set<UserEntity> followers = new HashSet<>();
}
Whenever two users follow each other, the application throws a java.lang.StackOverflowError
. How can I prevent this error while maintaining the relationship between user and followings
and followers
?
What I’ve Tried:
- Using
@JsonIgnoreProperties
on thefollowings
andfollowers
fields to prevent infinite recursion.
Expected Behavior:
When I retrieve a user, I should be able to see their followers and the users they are following.
Actual Behavior:
When two users follow each other, the application crashes with a java.lang.StackOverflowError
. And Also when i get all the users, i can see the followings of the each user but when i get user by username, it doesnt fetch the followings