Spring Boot中的多级子菜单JSON。

问题描述 投票:0回答:1

我在表中有一些记录有父子关系,截图如下。enter image description here

我如何写一个JPA实体来检索这些记录与父子关系的关系。希望得到您的帮助。

对我帮助不大的代码如下。

@Entity
@Table(name = PlatformConstant.TABLE_MENU)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Menu implements Serializable {

   private static final long serialVersionUID = 1L;

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

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

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

   @Column(name = "qr_code")
   private Blob qrCode;

   @JsonManagedReference
   @OneToMany(mappedBy = "parent")
   private Set<Menu> children;

   @ManyToOne
   @JsonBackReference
   private Menu parent; 
}

我上面的代码有以下错误的输出。 enter image description here

使用JpaRepository find all, 并应用@lucid的答案, 新的输出如下:

这段代码:

@Autowired
private MenuService menuService;

@CrossOrigin
@GetMapping("/all")
@ResponseBody
public List<Menu> getMenus() {
    return (List<Menu>) menuService.findAll().stream()
             .filter (menu-> Objects.isNull(menu.getParent()).collect(Collectors.toList()));
}

的输出。

enter image description here

谢谢你。

java spring-boot spring-data-jpa
1个回答
2
投票

Jackson 提供这些注解来控制父子关系。

@JsonBackReference:在序列化过程中跳过属性。

@JsonManagedReference:前向引用和序列化注解属性

在你的情况下,你不希望 parent 对象在你的子引用中被序列化,你可以在它的子引用中使用 @JsonBackReference

@JsonManagedReference
@OneToMany(mappedBy = "parent")
private Set<Menu> children;

@ManyToOne
@JsonBackReference
private Menu parent;

现在,要想从响应中删除子对象,我们可以像这样进行过滤

menuService.findAll().stream()
     .filter(menu-> Objects.isNull(menu.getParent()))
     .collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.