【问题标题】:How to expose many to many relationship in spring boot如何在spring boot中暴露多对多关系
【发布时间】:2018-03-17 19:45:52
【问题描述】:

我面临一个问题..我在 Spring Boot 中与 jpa 有多对多的关系,但我需要公开以下内容 产品有很多标签,标签有很多产品

如果查询产品/1

{product:{name:"product 1"}, tags:[ tag1:{name:"tag 1"}, tag2:{name:"tag2"} ] }

如果查询标签/1

{tag:1, products:[ product1:[{name:"product 1"}, tag2:{product:"tag2"} ] }

用弹簧靴休息的方法是什么? 一个例子,网址或想法,它会很有用。

【问题讨论】:

  • 不确定您想要什么。您是否正在寻找将这些映射到 JPA 实体的方法?
  • 啊抱歉我已经有了映射工作,但也许你知道当你尝试将它公开为休息时(转换为 json)有一个无限递归异常,因为双方的关系..我是什么我正在寻找一种新的观点,可以像我的例子一样将其暴露为休息,也许我没有很好地解决这个问题并且有一个最好的方法
  • 试试这个链接:baeldung.com/…
  • 因此,如果您的 JPA 映射正常工作,那么问题与 JPA 无关,而与 JSON 无关,因此请从问题中删除 JPA 标记

标签: java spring rest jackson


【解决方案1】:

当您尝试序列化 JPA bean 时,您需要结合使用 @JsonManagedReference@JsonBackReference 注释来阻止无限递归的发生。

请查看其中一些问题以获取更多信息:

【讨论】:

    【解决方案2】:

    multiple alternatives to stop infinite recursion:

    1. @JsonManagedReference@JsonBackReference:
    @Entity
    public class Product {
        @ManyToMany
        @JsonManagedReference
        private List<Tag> tags = new ArrayList<Tag>();
    }
    
    @Entity
    public class Tag implements {
        @ManyToMany(mappedBy = "tags")
        @JsonBackReference
        private List<Product> products = new ArrayList<Product>();
    }
    
    1. @JsonIdentityInfo:
    @Entity
    public class Product {
        @ManyToMany
        private List<Tag> tags = new ArrayList<Tag>();
    }
    
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    @Entity
    public class Tag implements {
        @ManyToMany(mappedBy = "tags")
        private List<Product> products = new ArrayList<Product>();
    }
    
    1. @JsonIgnoreProperties:
    @Entity
    public class Product {
        @ManyToMany
        @JsonIgnoreProperties("products")
        private List<Tag> tags = new ArrayList<Tag>();
    }
    
    @Entity
    public class Tag implements {
        @ManyToMany(mappedBy = "tags")
        @JsonIgnoreProperties("tags")
        private List<Product> products = new ArrayList<Product>();
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 2023-04-10
      • 2020-09-02
      相关资源
      最近更新 更多