首页 > 解决方案 > 从休息控制器返回对象时获得无限行输出?

问题描述

我一直在从事个人项目,无法修复此错误。

我是 Spring 引导和休息控制器的新手。当我将我的 Product 实体从 RestController 返回给我的邮递员时,它会提供无限的输出。请给我一些建议。

我正在使用 mysql 数据库

package com.example.hackernews.entity;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "products")
public class  Product {

    @Id
    @Column(name = "id", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int id;

    @Column(name = "name")
    String name;

    @Column (name="price")
    Interger price;


    @JoinColumn(name = "customer_id")
    @ManyToOne
    Customer customer;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name ) {
        this.name = name;
    }
 
    public Integer getPrice() {
        return price;
    }

    public void setPrice(Interger price ) {
        this.price = price;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer ) {
        this.customer = customer;

    }


}

提前致谢。

标签: javaspringspring-bootspring-restcontroller

解决方案


我添加了“JsonIgnore”注释以防止您遇到错误。检查此代码,让我知道它是如何工作的。

包 com.example.hackernews.entity;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore; 

@Entity
@Table(name = "products")
public class Product {

    @Id
    @Column(name = "id", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int id;

    @Column(name = "name")
    String name;

    @Column(name="price")
    Interger price;

    @JoinColumn(name = "customer_id")
    @ManyToOne
    @JsonIgnore
    Customer customer;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
 
    public Integer getPrice() {
        return price;
    }

    public void setPrice(Interger price) {
        this.price = price;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }


}

推荐阅读