java - 获取嵌套实体数据导致 stackoverflow 错误

标签 java spring-boot jpa jpql

我在两个表 User 和 Joke 之间有多对多关系。它们通过连接表 fav_joke 连接起来,该表保存这些表中的 id 值。根据我的设置方式,当我从这些表中插入和删除时,它似乎可以正常工作。

问题是当我尝试查询我的用户表以获取所有关联的笑话时。再次工作正常,但以某种初始形式重复它,最终导致 StackOverflow 错误。请参阅图片以查看响应。正如您所看到的,我在笑话中得到了一个用户,而该用户又拥有自己的笑话,该笑话也有自己的用户,并且一直持续下去...

Issue snapshot

当我进行此查询时,我只期望用户下有关联的笑话,在本例中应该是 2,仅此而已。我认为这与我在笑话实体中使用 @ManyToMany 关系注释有关,但我相信我需要它。请指教。谢谢。

实体

@Getter
@Setter
@NoArgsConstructor
@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    long memberId;

    @ManyToMany
    @JoinTable(
        name = "fav_joke",
        joinColumns = @JoinColumn(name = "memberId"),
        inverseJoinColumns = @JoinColumn(name = "id")
    )
    private Set<Joke> jokes;
}  

@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "joke")
public class Joke {

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

    private String question;
    private String answer;
    private boolean isFav;

    @ManyToMany(mappedBy = "jokes")
    private Set<User> users;
}

存储库

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User getUserByMemberId(long memberId);
}

@Repository
public interface JokeRepository extends JpaRepository<Joke, Long> {
    @Query("select j from Joke j where j.id =:id")
    Joke getJokeById(long id);
}

Controller - 此调用是导致堆栈溢出的调用。

@GetMapping("/get/fav/member_id/{memberId}")
public Set<Joke> getAllFavJokes(@PathVariable long memberId){
    User user = userRepository.getUserByMemberId(memberId);
    return user.getJokes();
}

我认为这不相关。只是添加它以防万一。执行此操作会填充由于多对多映射而动态创建的 fav_joke 表。

@GetMapping("/fav/joke_id/{id}/member_id/{memberId}/isFav/{isFav}")
    public String toggleFavJoke(@PathVariable long id, @PathVariable long memberId, @PathVariable boolean isFav){
        Joke joke = jokeRepository.getJokeById(id);
        User user = userRepository.findById(memberId).orElse(null);

        if(user != null && joke != null){
            if(user.getJokes() != null){
                if(isFav){
                    user.getJokes().remove(joke);
                }else {
                    user.getJokes().add(joke);
                }
            }else {
                if(!isFav){
                    user.setJokes(Stream.of(joke).collect(Collectors.toSet()));
                }
            }
            userRepository.save(user);
            return "Fav toggled successfully";
        }
        return "Unable to add fav. Invalid user or joke";
    }

当前表内信息如下:(笑话表有 1k+ 行)

Table Data

更新

按照评论中的建议添加了 @@JsonIdentityInfoannotation。堆栈溢出问题现已消失,但附加信息的方式不正确。

这是我得到的 JSON 格式。

[{
    "id": 5,
    "question": "What is a gas station's favorite type of shoe?",
    "answer": "Pumps.",
    "users": [{
        "memberId": 1,
        "jokes": [5, {
            "id": 7,
            "question": "What kind of place should you never take a dog?",
            "answer": "To the Flea Market.",
            "users": [1],
            "fav": false
        }, {
            "id": 8,
            "question": "What do you call a cow in an earthquake?",
            "answer": "A milkshake!",
            "users": [1],
            "fav": false
        }, {
            "id": 6,
            "question": "Why was 6 afraid of 7?",
            "answer": "Because 7 8 9!",
            "users": [1],
            "fav": false
        }, {
            "id": 4,
            "question": "Why was Dracula put in jail?",
            "answer": "He tried to rob a blood bank.",
            "users": [1],
            "fav": false
        }]
    }],
    "fav": false
}, 7, 8, 6, 4]

奇怪的是,只有第一个笑话保留在顶部,其余的则不断附加到内部的用户列表中,如上面所描述的。

我期待以下内容(并计划排除内部用户数据)。

[
    {
        "id": 6,
        "question": "J1 What is a gas station's favorite type of shoe?",
        "answer": "Pumps.",
        "users": [{
            "memberId": 1,
            "jokes": [5]
        }],
        "fav": false
    },
    {
        "id": 6,
        "question": "J2 What is a gas station's favorite type of shoe?",
        "answer": "Pumps.",
        "users": [{
            "memberId": 1,
            "jokes": [6]
        }],
        "fav": false
    },
    {
        "id": 7,
        "question": "J3 What is a gas station's favorite type of shoe?",
        "answer": "Pumps.",
        "users": [{
            "memberId": 1,
            "jokes": [7]
        }],
        "fav": false
    }
] 

最佳答案

您可以使用@JsonIgnoreProperties来打破循环:

public class Joke {

    @JsonIgnoreProperties("jokes")
    public Set<User> getUsers(){
        return this.users;
    }    
}  

如果您获取 User ,也可能会发生同样的问题,因此您可能还需要打破 User 的循环:

public class User {

    @JsonIgnoreProperties("users")
    public Set<Joke> getJokes(){
        return this.jokes;
    }    
}  

关于java - 获取嵌套实体数据导致 stackoverflow 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57444425/

相关文章:

java - 在cmd中运行javac和javah时,显示javac : file not found

java - Spring Boot 错误 : java. lang.NoClassDefFoundError: org/springframework/util/Assert

java - Spring Cloud Zuul CircuitBreaker 所有路由均通过 TurbineStream 而不是 Turbine-AMQP

java - 使用 JPA/Hibernate 创建引用实体(如果为 null)

java - 如何通过 key 获得锁

java - 在没有证书的情况下通过 ssl 连接

java - 使用 JPA 存储库的 Hibernate 获取配置文件

java - JPA 持久性.xml

java - JJWT 库和处理过期 ExpiredJWTException

java - 如何为整个Spring Boot应用程序生成 token