spring-mvc - JPA / Spring MVC Rest API - 同一实体中的一对多关系
问题描述
我 2 天前开始使用 Spring MVC,但在案例研究中遇到了一些问题。 我创建了一个基本表类别(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,名称 = ...,等等,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
}
推荐阅读
- javascript - 左侧赋值无效
- java - 如何在 JTextField 中放置随机数生成器
- email - 在 Cognito 中,我如何在请求更改新的错误电子邮件后回滚我的旧电子邮件
- http - HTTP 客户端在超时时返回随机错误
- python - 将列表复制到 numpy 数组中会将浮点数转换为字符串
- git - Docker 上的 Jenkins 无法连接到本地仓库
- angular - Angular Dragula DropModel 事件仅从左到右触发
- regex - 记事本正则表达式替换根据需要重复
- python - 如何在excel中将单元格按类别合并为一个
- django - 如何使用 docker 部署 django-q worker?