我如何写一个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;
}
使用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()));
}
的输出。
谢谢你。
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());