【问题标题】:Spring jpa hibernate how to map a relationship to multiple objects of the same entitySpring jpa hibernate如何将关系映射到同一实体的多个对象
【发布时间】:2021-12-11 07:34:42
【问题描述】:

我正在使用 Spring boot 创建一个航空公司应用程序,并且有一个名为 Flight 的实体具有同一实体的两个属性:

public class Flight {

    // more code here

    @ManyToOne
    @JoinColumn(name = "airport_id", referencedColumnName = "id")
    private Airport startLocation;

    @ManyToOne
    @JoinColumn(name = "airport_id", referencedColumnName = "id")
    private Airport destination;

    // more code here
}

机场具有航班列表的 OneToMany 关系。

如何正确映射这种关系? Spring 现在给了我错误:

mappedBy 引用了一个未知的目标实体属性(airport-flights)

提前致谢。

【问题讨论】:

    标签: java spring spring-boot hibernate


    【解决方案1】:

    在 Airport Entity 中定义关系,并指定属性 mappedBy=""。 MappedBy 基本上告诉hibernate不要创建另一个连接表,因为该关系已经被该关系的相反实体映射。

    这基本上是指航班实体中使用的变量,例如 startLocation 和 destination。 它应该是这样的:-

    public class Airport {
      ...
      @OneToMany(mappedBy = "startLocation")
      private Flight flight_departure_location;
    
      @OneToMany(mappedBy = "destination")
      private Flight flight_destination;
    }
    

    应该是这样的。

    【讨论】:

      【解决方案2】:

      在机场实体内部,mappedBy 引用应如下所示...

      @OneToMany(mappedBy = "startLocation")

      @OneToMany(mappedBy = "目的地")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多