【问题标题】:Relationship between rest resources with Spring bootREST资源与Spring boot的关系
【发布时间】:2019-01-24 11:44:45
【问题描述】:

我正在学习 Spring Boot Rest,但我无法解决问题。有人能帮我吗? 我在 Product 和 Category 实体之间创建了以下映射:

类别实体:

@Entity
public class Category {
 ...
@JsonIgnore
@OneToMany(mappedBy="category")
private List<Product> products;
//getters setters
}

产品实体:

@Entity
@Table(name="lancamento")
public class Lancamento {
...
@NotNull
@ManyToOne
@JoinColumn(name="id_pessoa")
private Pessoa pessoa;
//getters setters
}

我等待这个结果:

{
 "name":"Category_1",
  "products":[
     {
       "id":"1",
       "name":"Product_1"
     },
     {
      "id":"2",
       "name":"Product_2"
     },
   ]
}

但真正的结果是:

{
 "name":"Category_1"
}

怎么了?我需要进行一些设置吗? 谢谢。

【问题讨论】:

    标签: json spring rest spring-boot


    【解决方案1】:

    尝试删除@JsonIgnore 注释。使用此注释,您基本上是在告诉 Spring 在序列化/反序列化对象时 ignore 该字段,因此它不会出现在输出中。

    See the Docs

    【讨论】:

      【解决方案2】:

      您在 Category 的 products 字段中有 JsonIgnore

      【讨论】:

        【解决方案3】:

        移除@JsonIgnore注解。

        由于@JsonIgnore 注释,此列表将被忽略。

        查看此https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonIgnore.html 以了解@JsonIgnore

        【讨论】:

          【解决方案4】:

          您必须移除 @JsonIgnore 并使用 DTO 对象进行序列化。无论如何,这是创建 API 的正确方法。您可以根据需要组合和转换 DTO 中实体的所有数据。

          您可以将反向关系(字段)放在 Product 对象中,例如

          @JsonIgnore
          @ManyToOne
          private Category category;
          

          并用@JsonIgnore 标记该字段。

          这取决于你,但更好的方法是使用 DTO

          【讨论】:

            【解决方案5】:

            谢谢大家,我在Infinite Recursion with Jackson JSON and Hibernate JPA issue找到了解决方案

            这种情况的解决方案是使用 Jackson 注释:@JsonManagedReference 和 @JsonBackReference。

            类别:

            @Entity
            public class Category {
            ...
            @JsonManagedReference 
            @OneToMany(mappedBy="category")
            private List<Product> products;
            //getters setters
            }
            

            产品

            @Entity
            public class Product {
            ...
            
            @JsonBackReference
            @NotNull
            @ManyToOne
            @JoinColumn(name="id_product")
            private Product product;
            //getters setters
            }
            

            这就像我需要的那样工作。

            【讨论】:

              猜你喜欢
              • 2018-09-21
              • 2016-06-06
              • 1970-01-01
              • 2017-01-09
              • 1970-01-01
              • 2014-01-03
              • 1970-01-01
              • 1970-01-01
              • 2021-04-13
              相关资源
              最近更新 更多