我正在使用 Spring Boot 开发一个 Java 应用程序,并且我有一个
UserEntity
类,用户可以在其中互相关注。然而,当两个用户相互关注时,我遇到了java.lang.StackOverflowError
。这是我当前的UserEntity
课程:
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<>();
}
每当两个用户相互关注时,应用程序就会抛出一个
java.lang.StackOverflowError
。如何在维护用户与 followings
和 followers
之间的关系的同时防止此错误?
@JsonIgnoreProperties
和 followings
字段上使用 followers
可以防止无限递归。当我检索用户时,我应该能够看到他们的关注者以及他们正在关注的用户。
当两个用户互相关注时,应用程序会崩溃并伴有
java.lang.StackOverflowError
。另外,当我获取所有用户时,我可以看到每个用户的以下内容,但是当我通过用户名获取用户时,它不会获取以下内容
我认为你的代码运行良好..
我写了测试代码
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
public User test() {
long userId = 1L;
User user = userRepository.findById(userId).orElseThrow();
User follower = User.builder()
.userName("follower")
.password("follower")
.followers(new HashSet<>())
.followings(new HashSet<>())
.build();
user.getFollowers().add(follower);
follower.getFollowings().add(user);
userRepository.save(follower);
return follower;
}
}
@RestController
@AllArgsConstructor
public class TestController {
private final UserService userService;
@GetMapping("/test")
public User test() {
return userService.test();
}
}
我得到了这个回复
{
"id": 2,
"userName": "follower",
"password": "follower",
"followings": [
{
"id": 1,
"userName": "user1",
"password": "user1"
}
],
"followers": []
}