我试图在前端使用Angular设置Spring MVC Rest API。 我绝对是这两种技术的初学者,这是一个真正的挑战。
我要说的很对:我有一个引用自身的实体。例如,一个类别可以有一个父类别...为此,我从一个现有表中生成了一个实体...
我尝试使用fetch = fetchtype.eager来获取数据,但未提供预期的结果。
这是我的实体:
package com.company.app.model;
import java.io.Serializable;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import java.util.Date;
import java.util.List;
@Entity
@Table(name="categories")
@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
....
//bi-directional many-to-one association to Category
@ManyToOne
@JsonManagedReference
private Category category;
//bi-directional many-to-one association to Category
@OneToMany(mappedBy="category", fetch = FetchType.EAGER)
@JsonBackReference
private List<Category> categories;
//bi-directional many-to-one association to CategoryProduct
@OneToMany(mappedBy="category")
@JsonBackReference
private List<CategoryProduct> categoryProducts;
public Category() {
}
// Getters, setters and other methods generated with JPA
}
我的问题是我想生成一个Json,其中的“顶级”类别没有父母及其所有子类别。从技术上来说看起来像这样
[
{
// Top level category
"id":1,
"name":"....",
"desc": "....."
"children" : [
{
"id":12,
"name":"....",
"desc": "....."
},
{
"id":14,
"name":"....",
"desc": "....."
}
...
]
"admin":{
"id":1,
"createdAt":1541869810000,
"deletedAt":null,
"email":"david.vera@9online.fr",
"login":"admin",
"name":"Vera",
"password":"admin",
"surname":"David",
"updatedAt":1542150000000
},
}
]
在我的控制器中,我有一种列出类别的方法,它可以按预期工作。
@GetMapping(path="/categories", produces= {"application/json"})
public List<Category> getAllCategories(Model model) {
return categoryRepository.findAll();
}
感谢您的帮助