gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:53:44 25 4
gpt4 key购买 nike

我有两个具有 @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../
}

在我的 Controller 中,我有一个功能/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();
}

这是我得到的 stage 对象:

{"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 而不是实体详细信息,请创建 getProductIDgetCategoryID 方法,并使用 @JsonIgnore 注释实体访问器。

关于spring - JPA - Spring boot -@OneToMany 持久性工作正常,但返回 Json 对象时我得到一个奇怪的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28000834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com