【问题标题】:How to create a 3 way bi-directional relationship with @JsonManagedReference and @JsonBackReference in JPA/Hibernate如何在 JPA/Hibernate 中使用 @JsonManagedReference 和 @JsonBackReference 创建 3 向双向关系
【发布时间】:2022-01-11 15:07:33
【问题描述】:

我的实体是这样设置的:

客户

    @Entity
    @Table(name = "client")
    public class Client {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        
        ...
    
        @OneToMany(mappedBy = "client")
        @JsonManagedReference
        private List<Project> projects;
    }

项目

    @Entity
    @Table(name = "project")
    public class Project {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        
        ...
    
        @ManyToOne(name= "client")
        @JsonBackReference
        private Client client;

        @OneToMany(mappedBy = "project")
        @JsonManagedReference
        private List<Listing> listings;
    }

上市

@Entity
    @Table(name = "listing")
    public class Listing{
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        
        ...

        @ManyToOne(name= "project")
        @JsonBackReference
        private Project project;
    }

目前,如果我通过 ID 呼叫特定客户,那么我将获得客户、他们的项目以及该项目的列表。这可以正常工作。但是,当我通过 ID 调用项目时,我只会得到该项目的列表,我还想知道哪个客户拥有该项目。同样,当我通过 ID 调用列表时,我只收到具有该 ID 的列表,我还想要拥有该列表的项目以及拥有它的客户,这可能吗?谢谢。

【问题讨论】:

  • 有很多关于 JsonBackReference 的教程(参见baeldung.com/…)表明它将被排除在 JSON 之外 - 所以它不会按照你想要的方式运行。包含客户端将序列化其所有项目,因此您不妨直接获取客户端本身,因为它将将此项目包含在其项目中。

标签: java database hibernate jpa spring-data-jpa


【解决方案1】:

注意:

@JsonManagedReference 是引用的前向部分——正常序列化的部分。 @JsonBackReference 是引用的后面部分——它将从序列化中省略。 序列化的 Item 对象不包含对 Client 对象的引用。

使用@JsonIdentityInfo

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class, 
  property = "id")
public class Client

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class, 
  property = "id")
public class Project

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class, 
  property = "id")
public class Listing

更多信息在这里:https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2015-09-27
    • 2016-11-07
    相关资源
    最近更新 更多