我有两个模型类。一个是

@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]]

最佳答案

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

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

这样,错误将更有意义,因为它会打印参考名称而不是'defaultReference'。

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

07-25 23:43