代码之家  ›  专栏  ›  技术社区  ›  davidvera

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

  •  0
  • davidvera  · 技术社区  · 6 年前

    我在两天前开始使用SpringMVC,我通过一个案例研究遇到了一些问题。 我创建了一个基本表categories(category_id指一个category 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`);
    

    现在我的问题是显示类别的完整列表及其子类别(如果存在的话)。。。

    @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": [
    
        ]
     ....
    }
    

    1 回复  |  直到 6 年前
        1
  •  0
  •   davidvera    6 年前

    以下是我找到的解决方案:

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