【发布时间】:2015-01-17 15:12:32
【问题描述】:
我有两个实体( 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();
}
这是我得到的战略对象:
{"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":
【问题讨论】:
-
为什么奇怪?你期待什么?
-
我希望只有类别的 ID,而不是像这样的所有对象:{ "cid":1, "name":"LIGA", "description":"messi feghouli cristiano" , "products":[{ "price":200, "name":"Real Madrid", "description":"jahd besaf", "category":1 }] }
-
不,你得到了整个对象层次结构。
-
是的,我知道,但我所拥有的是正确的
-
即使它是无限的?因为在检索它时,我在 spring boot 中有错误告诉我:getOutputStream() 已经为此响应调用
标签: spring jpa persistence spring-boot one-to-many