【发布时间】:2020-12-26 17:20:10
【问题描述】:
我在春季有 2 个实体:具有 OneToMany 关系的类别和位置:
Category.java:
@Table(name = "category")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
int parentId;
String name;
@OneToMany(mappedBy = "category")
@JsonManagedReference(value = "referenceCallInCategory")
List<Position> positionList;
// getters and setters
位置.java:
@Entity
public class Position {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
String position;
String company;
String description;
@ManyToOne
// @JsonBackReference (value = "referenceCallInPosition")
@JsonIgnoreProperties({"parentId","name","positionList"})
Category category;
// getters and setters
当我通过邮递员发布职位请求时,我在终端中收到以下警告:WARN 15904 --- [nio-8080-exec-2] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class positionsSite.positions.mode l.Position]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'referenceCallInCategory': no back reference property found from type [collection type; class java.util.List, contains [simple type, class positionsSite.positions.model.Position]]
奇怪的是,在对类别进行后请求时,会出现完全相同的警告,但是在我对类别进行后请求后,位置的后请求工作没有问题。直到我重新启动应用程序,它才会再次失败。
我使用@JsonIgnoreProperties 而不是@JsonBackReference 的原因是,当我请求获取职位时,我需要Category.id。鉴于警告找不到反向引用属性,我尝试了代码中注释的@JsonBackReference,但这并没有改变任何东西。
任何有关如何解决此问题的帮助将不胜感激
【问题讨论】:
-
与问题无关,但您是否考虑过为什么要设置私有变量(如果有)?如果你可以同时获取和设置一个私有变量,它应该是私有的吗?
-
另外,this 的帖子是否对您有帮助,或者您是否熟悉不同的
@Json的工作原理? -
@darclader 自从我上次使用不同的
@Json属性以来,它已经退出了一段时间。我以为我仍然很了解他们,但你提到的帖子对我的记忆产生了奇迹,所以谢谢:)。如果我使用@JsonIgnoreProperties,则不需要@JsonManagedReference。 -
@darclader 关于 getter 和 setter:你说得对。这更多的是开发时的便利问题。这不是最简洁的工作方式,但我的一些习惯是先创建所有 getter 和 setter,然后删除我做/不应该使用的那些,并进行更大的安全检查