如何使用Spring Boot和MYSQL为多级菜单列表创建嵌套的JSON?

时间:2019-05-23 11:15:01

标签: mysql json spring-boot jpa orm

我一直在尝试使用MySQL和Spring boot创建多级嵌套JSON。

我将需要此JSON,以便以后可以使用jQuery创建HTML菜单。

但是我目前正在努力创建多层嵌套JSON。

基本上,我有一个看起来像这样的MYSQL数据库:

id    categoryItem    parrent

1     car               0
2     red car           1
3     blue car          1
4     bike              0
5     yellow bike       4

post_parent列是将它们链接在一起的列。

我尝试使用以下Spring引导代码,但JSON输出错误。

我的实体类如下:

@Table(name = "category_item")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class CategoryItem implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "fa_icon")
    private String faIcon;

    @ManyToOne
    @JsonIgnoreProperties("categoryItems")
    private CategoryItem parrent;
}

我将需要像这样的结构的多层嵌套JSON:

{
  "id": 1,
  "name": "car",
  "categoryItem": [
    {
      "id": 2,
      "name": "red car"
    },
    {
      "id": 3,
      "name": "blue car"
    }
  ]
}

我该如何处理!!请帮忙!

1 个答案:

答案 0 :(得分:0)

您需要使其成为双向关系:

@Table(name = "category_item")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class CategoryItem implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "fa_icon")
    private String faIcon;

    @OneToMany(mappedBy = "parent")
    private Set<CategoryItem> categoryItems;

    @ManyToOne
    @JsonIgnoreProperties("categoryItems")
    private CategoryItem parent;
}