首页 > 解决方案 > 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": [

    ]
 ....
}

谢谢你的帮助。

标签: spring-mvcspring-data-jpa

解决方案


这是我找到的解决方案:

@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
}

推荐阅读