JPA/Spring MVC Rest API-同一实体中的一对多关系



我两天前开始使用SpringMVC,在一个案例研究中遇到了一些问题。我创建了一个基本的表类别(category_id指类别id(:

DROP TABLE IF EXISTS `categories`;
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL,
`category_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_CATEGORY_CATEGORY` (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `categories`
ADD CONSTRAINT `FK_CATEGORY_CATEGORY` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`);

现在我的问题是显示他们的孩子的完整类别列表,如果他们存在的话。。。

我的控制器中有一个方法,它以JSON形式返回列表:

@GetMapping(path="/categories", produces= {"application/json"})
public List<Category> getAllCategories(Model model) {
return categoryRepository.findAll();
}

建议这样做:

public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
@ManyToOne
private Category parentCategory;
@OneToMany(mappedBy="parentCategory", fetch = FetchType.EAGER)
private List<Category> childCategories;

... default constructor, getters & setter etc.
}

在尝试查看页面时,我可以看到类别,但我不显示它们是否有子类别。。。。例如,这个类别应该给出一个儿童类别列表。。。例如,我应该在子类别中id=5,name=。。。,等等,id=6,id=7…

{
"id": 1,
"name": "XXX",
"createdat": 1541872732000,
"updatedat": 1541872732000,
"parentCategory": null,
"childCategories": [
]
....
}

并且这个有父类别的类别不返回父类别,而parentCategory值应该是1:

{
"id": 14,
"name": "xxxxxx",
"createdat": 1541873447000,
"updatedat": 1541873447000,
"parentCategory": null,
"childCategories": [
]
....
}

谢谢你的帮助。

这是我找到的解决方案:

@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(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;
@Column(name="name")
private String name;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="category_id")
@JsonBackReference
private Category parentCategory;
@OneToMany(mappedBy="parentCategory", fetch = FetchType.EAGER)
@JsonManagedReference
private List<Category> childCategory;
public Category() {
}
public Category(String name) {
this.name = name;
}
// getters & setters
}

最新更新