• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

无法获取json:无限递归

java 3次浏览

我在尝试对发布者存储库执行GET时遇到无限循环。

发布者:

@Data
@AllArgsConstructor
@Entity
@Table(name = "publisher")
public class Publisher {

    @Id
    private Long publisherID;

    private String name;
    private String location;

    public Publisher(@JsonProperty("publisherID") Long publisherID,
                     @JsonProperty("name") String name,
                     @JsonProperty("location") String location) {
        this.publisherID = publisherID;
        this.name = name;
        this.location = location;
    }

    @JsonManagedReference(value="Book-Publisher")
    @OneToMany(mappedBy = "publisher", cascade = CascadeType.ALL)
    private Set<Book> books;

    public Publisher() {
    }
}

书:

@Data
@AllArgsConstructor
@Entity
@Table(name = "book")
public class Book {

    @Id

私人Long ID;

private String name;

@JsonBackReference(value="Book-Publisher")
@ManyToOne
@JoinColumn(name="publisherID")
private Publisher publisher;

private int publicationYear;
private int amount;

@JsonManagedReference(value="BookAuthors-Book")
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
private Set<BookAuthors> bookAuthors;

@JsonManagedReference(value="BookGenres-Book")
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
private Set<BookGenres> bookGenres;

public Book(@JsonProperty("id") Long id,
            @JsonProperty("name") String name,
            @JsonProperty("publisherID") Long publisherID,
            @JsonProperty("publicationYear") int publicationYear,
            @JsonProperty("amount") int amount) {
    this.id = id;
    this.name = name;
    this.publicationYear = publicationYear;
    this.amount = amount;
    PublisherService publisherService = BeanUntil.getBean(PublisherService.class);
    this.publisher = publisherService.findByID(publisherID).get();

}
@JsonManagedReference(value="RentedBook-Book")
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
private Set<RentedBook> rentedBooks;

public Book() {
}

}

2020-04-10 16:43:02.483 WARN 672-[nio-8080-exec-6] .wsmsDefaultHandlerExceptionResolver:已解决[org.springframework.http.converter.HttpMessageNotWritableException:无法编写JSON:无限递归(StackOverflowError) ;嵌套的异常是com.fasterxml.jackson.databind.JsonMappingException:无限递归(StackOverflowError)(通过参考链:java.util.ArrayList [0]-> com.vanyasav.domain.Publisher [“ books”])]

完整的代码在这里:

https://github.com/vanyasav/Library

解决方案如下:

当对Publisher的列表进行序列化以响应时,将调用Publisher字段的所有getter方法。因此,Publisher关系字段books的getter也称为setvalue。这是递归发生的,这是无限递归的原因。

最好不要使用Entity作为响应。为发布者创建DTO类,然后将发布者实体值映射到DTO,然后发送响应。

要将一个模型动态映射到另一个模型,可以使用ModleMapper


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)