【问题标题】:Spring boot - no back reference property found from type[]Spring boot - 没有从 type[] 中找到反向引用属性
【发布时间】: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,然后删除我做/不应该使用的那些,并进行更大的安全检查

标签: java spring jackson


【解决方案1】:

正如@darclader 所提到的,this post 清楚地说明了不同的@Json 属性。我的错误是我仍然有一个@JsonManagedReference 这给了问题。我删除了它,但并非一切都完美。

【讨论】:

  • 很高兴听到我的评论有帮助!如果您愿意,可以将此设置为答案,以帮助将来遇到类似问题的人:)。
猜你喜欢
  • 2018-10-08
  • 2021-03-05
  • 2016-09-18
  • 2015-08-15
  • 2021-12-25
  • 2016-08-01
  • 2015-08-20
  • 1970-01-01
  • 2021-12-26
相关资源
最近更新 更多