I have two model classes. One is
@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;
}
and the second is
@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;
}
But on save I'm getting this error:
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]]
The exception you are facing stems from the MappingJackson2HttpMessageConverter.
To fix it swap the annotations so you get this :
public class UserTools {
...
@JsonBackReference
private List<UserToolsHistory> userToolsHistory;
...
}
public class UserToolsHistory {
....
@JsonManagedReference
private UserTools userTools;
----
}
This tutorial explains how it must be done : jackson-bidirectional-relationships-and-infinite-recursion
@JsonManagedReference
and @JsonBackReference
and replacing it with @JsonIdentityInfo
In order to make troubleshooting easier, you can add a different name to each @JsonManagedReference
and @JsonBackReference
, for example:
@JsonManagedReference(value="userToolsHistory")
private List<UserToolsHistory> userToolsHistory;
This way the error is more meaningful because it prints the reference name instead of 'defaultReference'.
Please indicate which enity you are trying to serialize - UserTools
or UserToolsHistory
? Anyway you can try adding getters and setters to your entities and then add @JsonIgnore
to the "get{Parent}()" in the "child" class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With