【问题标题】:Java Sprint MVC JSON infinite recursionJava Spring MVC JSON 无限递归
【发布时间】:2023-03-26 13:16:01
【问题描述】:

您好,我有一个非常简单的结构,其中有以下课程。 在对用户列表进行选择时,我得到 JSON 无限递归。 我尝试输入@JsonManagedReference 和@JsonBackReference,我得到的只是我不再获得JSON 无限递归,但是如果您查看我上传的图像,您会看到来自服务器的丑陋响应。

public class Organisations extends SuperModel implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "parent_id", nullable = true)
    private Organisations parent;

    @OneToMany(mappedBy = "parent")
    private List<Organisations> childs = new ArrayList<Organisations>(); }

public class Permissions extends SuperModel implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    private Users user;

    @NotNull
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "organisation_id", nullable = false)
    private Organisations organisation;
}

public class Roles  extends SuperModel implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "organisation_id", nullable = false)
    private Organisations organisation;

    @NotNull
    @Size(min = 3, max = 20)
    @Column(name = "role", unique = true, nullable = false)
    private String role;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name="role_permissions", joinColumns=@JoinColumn(name="role_id"), inverseJoinColumns=@JoinColumn(name="permission_id"))
    private List<Permissions> permissions = new ArrayList<Permissions>();
}

public class Users extends SuperModel implements Serializable {

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

    @NotNull
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "organisation_id", nullable = false)
    private Organisations organisation;

    @NotNull
    @ManyToOne(optional = false)
    @OneToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "role_id", nullable = false)
    private Roles role;
}

This is an image from response

【问题讨论】:

  • 永远不要尝试序列化 json 中的递归数据结构
  • 似乎类的设计不当。你有很多多余的关系。从Permissions 中删除Users 字段或使用@JsonIgnore 注释标记Users。在后一种情况下,您必须手动设置此属性。
  • 尝试将实体取消代理到所需的深度。
  • @KenBekov Image 我有云系统,我应该知道哪个组织是任何记录的所有者,这就是我使用每个表的关系的原因。

标签: java json hibernate spring-mvc recursion


【解决方案1】:

@Javier 你的意思是删除可序列化接口的实现???你认为它会解决我的问题吗??

【讨论】:

    猜你喜欢
    • 2012-02-20
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2015-11-28
    • 2019-07-19
    • 2018-01-03
    • 1970-01-01
    • 2020-07-23
    相关资源
    最近更新 更多