jackson 使用Set而不是List会导致“无法写入JSON:无限递归”异常

bprjcwpo  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(139)

我收到错误 “无法写入JSON:无限递归”。我研究并找到了各种解决方案here@JsonManagedReference / @JsonBackReference@JsonIgnore@JsonIdentityInfo),但它们似乎都不起作用,最后我找到了一个answer,声明有必要从Set更改为List,为了让@JsonIdentityInfo解决方案工作。我测试了它,它在从Set更改为List后真正开始工作。
我觉得这很奇怪,但我发现了更奇怪的事情:在从Set更改为List之后,我删除了@JsonIdentityInfo注解,一切都继续工作。换句话说,我真正需要做的就是从Set更改为List以消除异常。没有其他任何事情。不需要任何解决方案:一个月五个月一个月,一个月六个月,一个月七个月。
下面是产生异常的代码。我所要做的就是将private Set<Permission> permission更改为private List<Permission> permission
我想知道为什么,特别是因为我更喜欢使用Set,以避免Hibernate使用“Bags”范例(这可能会导致some undesirable behaviors)。

权限.java:

@Entity
@Data
public class Permission{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotBlank
    private String name;

    @NotNull    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "category_of_permission_id")
    private CategoryOfPermission categoryOfPermission;    
}

权限类别.java:

@Entity
@Data
public class CategoryOfPermission{

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

    @NotBlank
    private String name;

    @NotNull    
    @OneToMany(mappedBy = "categoryOfPermission", fetch=FetchType.LAZY)
    private Set<Permission> permission;
}

权限存储库类别.java:

public interface CategoryOfPermissionRepo extends CrudRepository<CategoryOfPermission, Integer>{
}
gojuced7

gojuced71#

这是因为Java中的Set使用equals契约来确定两个对象是否相同,并且Permission类中的equals方法的实现方式(使用lombok)导致了无限递归。
它是Permissionequals方法的生成代码的一部分

Object this$categoryOfPermission = this.getCategoryOfPermission();
    Object other$categoryOfPermission = other.getCategoryOfPermission();
    if (this$categoryOfPermission == null) {
      if (other$categoryOfPermission != null) {
        return false;
      }
    } else if (!this$categoryOfPermission.equals(other$categoryOfPermission)) {
      return false;
    }

并且它是CategoryOfPermission类的生成代码

public boolean equals(final Object o) {
    if (o == this) {
      return true;
    } else if (!(o instanceof CategoryOfPermission)) {
      return false;
    } else {
      CategoryOfPermission other = (CategoryOfPermission)o;
      if (!other.canEqual(this)) {
        return false;
      } else {
        Object this$id = this.getId();
        Object other$id = other.getId();
        if (this$id == null) {
          if (other$id != null) {
            return false;
          }
        } else if (!this$id.equals(other$id)) {
          return false;
        }

        Object this$permission = this.getPermission();
        Object other$permission = other.getPermission();
        if (this$permission == null) {
          if (other$permission != null) {
            return false;
          }
        } else if (!this$permission.equals(other$permission)) {
          return false;
        }

        return true;
      }
    }
  }

如您所见,Permission类调用CategoryOfPermission类的equals方法,CategoryOfPermission调用Permision类的equals方法,这最终导致堆栈溢出问题!

相关问题