【问题标题】:Can not handle managed/back reference 'defaultReference': no back reference property found无法处理托管/反向引用“defaultReference”:找不到反向引用属性
【发布时间】:2016-09-18 19:59:03
【问题描述】:

我有两个模型类。一个是

@Entity(name = "userTools")
@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "assignToUser_id","toolsType_id" }))
@Inheritance(strategy = InheritanceType.JOINED)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "className")
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserTools {

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

    @OneToOne
    private ToolsType toolsType;

    @OneToMany(mappedBy = "userTools", fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval = true)
    @Cascade(org.hibernate.annotations.CascadeType.DELETE)
    @JsonManagedReference
    private List<UserToolsHistory> userToolsHistory;
}

第二个是

@Entity(name = "userToolsHistory")
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserToolsHistory {

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

    @OneToOne
    private ToolsType toolsType;

    @ManyToOne
    @JsonIgnore
    @JsonBackReference
    private UserTools userTools; 

    private String comments;
}

但保存时出现此错误:

Can not handle managed/back reference 'defaultReference': no back
reference property found from type [collection type; class
java.util.List, contains [simple type, class
com.dw.model.tools.UserToolsHistory]]

【问题讨论】:

    标签: java json spring rest


    【解决方案1】:

    为了使故障排除更容易,您可以为每个 @JsonManagedReference@JsonBackReference 添加不同的名称,例如:

    @JsonManagedReference(value="userToolsHistory")
        private List<UserToolsHistory> userToolsHistory;
    

    这样错误更有意义,因为它会打印引用名称而不是“defaultReference”。

    请指出您要序列化哪个实体 - UserToolsUserToolsHistory?无论如何,您可以尝试将 getter 和 setter 添加到您的实体中,然后将 @JsonIgnore 添加到“child”类的“get{Parent}()”中。

    【讨论】:

      【解决方案2】:

      您面临的异常源于 MappingJackson2HttpMessageConverter。

      要修复它,请交换注释,以便得到:

      public class UserTools {
      ...
      @JsonBackReference
      private List<UserToolsHistory> userToolsHistory;
      ...
      }
      
      public class UserToolsHistory {
      ....    
      @JsonManagedReference
      private UserTools userTools; 
      ----
      }
      

      本教程解释了必须如何完成:jackson-bidirectional-relationships-and-infinite-recursion

      【讨论】:

      【解决方案3】:

      @JsonManagedReference@JsonBackReference 并将其替换为 @JsonIdentityInfo

      【讨论】:

      • 也许这不应该是一个答案,而只是对问题/答案的评论
      • 不要cmet,因为声誉
      猜你喜欢
      • 2018-10-08
      • 2017-11-13
      • 2017-11-26
      • 1970-01-01
      • 2015-03-26
      • 2017-08-29
      • 2017-10-13
      • 2020-08-04
      • 1970-01-01
      相关资源
      最近更新 更多