JPA - Spring boot -@OneToMany 持久性工作正常但我在返回 Json 对象时得到一个奇怪的对象

JPA - Spring boot -@OneToMany persistence works fine but i get a strange object when returning Json object

我有两个实体 ( Category | product ) 具有 @OneToMany 双向关系。

@Entity
public class Category {

    public Category() {
        // TODO Auto-generated constructor stub
    }

    public Category(String name,String description) {
        this.name=name;
        this.description=description;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long cid;

    private String name;

    private String description;

    @OneToMany(mappedBy="category",cascade=CascadeType.ALL, orphanRemoval=true)
    private Set<Product> products;
    /..getters and setter.../

    }

    @Entity
    public class Product {
    public Product() {
        // TODO Auto-generated constructor stub
    }

    public Product(long price, String description, String name) {
        // TODO Auto-generated constructor stub
        this.name=name;
        this.description=description;
        this.price=price;

    }

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long pid;

    private long price;

    private String name;

    private String description;

    @ManyToOne  
    private Category category;
    /..getters and setters../
    }

在我的控制器中,我有一个功能 /categoris 可以为一个产品添加一个新类别,它工作得很好,在我的数据库中我有一个外国类别 ID

但是当我尝试使用 responseBody 检索所有类别时,我在类别中得到了一个奇怪的对象(我想要在产品类别中有:类别 ID 而不是对象本身)

public @ResponseBody Category create() {
    Category c=new Category("LIGA","messi feghouli cristiano");

    Product p=new Product(200,"jahd besaf","Real Madrid");

    if(c.getProducts()!=null){
        c.addProducts(p);
    }else{
        Set<Product> products=new HashSet<Product>();           
        products.add(p);
        c.setProducts(products);
    }
    p.setCategory(c);

    cDao.save(c);  pDao.save(p);        
    return c;
}


@RequestMapping(value="/categories",method = RequestMethod.GET)
public @ResponseBody List<Category> categories() {
    return cDao.findAll();
}

这是我得到的 strage 对象 :

{"cid":1,"name":"LIGA","description":"messi feghouli cristiano","products":[{"price":200,"name":"Real Madrid","description":"jahd besaf","category":{"cid":1,"name":"LIGA","description":"messi feghouli cristiano","products":[{"price":200,"name":"Real Madrid","description":"jahd besaf","category":{"cid":1,"name":"LIGA","description":"messi feghouli cristiano","products":[{"price":200,"name":"Real Madrid","description":"jahd besaf","category":{"cid":1,"name":"LIGA","description":"messi feghouli cristiano","products":

这正是它应该的样子。

如果您希望避免循环引用,请使用 @JsonBackReference 注释。这可以防止 Jackson(假设您使用的是 Jackson)进入无限循环并耗尽您的筹码。

如果您想要 ID 而不是实体详细信息,请创建 getProductID & getCategoryID 方法并使用 @JsonIgnore.

注释实体访问器