【问题标题】:Mapping two fields of the same class with One-to-One relationship使用一对一关系映射同一类的两个字段
【发布时间】:2022-12-14 09:51:32
【问题描述】:

我有一个 Flight 类和一个 AircraftReport 类。 AircraftReport 类包含一个入站航班和一个出站航班,我希望将它们映射为 @OneToOne。如何正确定义关系?

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table
public class Flight implements Serializable {
    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "flight_sequence"
    )
    @SequenceGenerator(
            name = "flight_sequence",
            allocationSize = 1
    )
    @Column(nullable = false, updatable = false)
    private Long id;

    private String callsign;
    private Date date;
    private String origin;
    private String destination;
    private String registration;
    private String aircraftType;

    @OneToOne(mappedBy = "--what should it be mapped by here--")
    private AircraftReport aircraftReport;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table
public class AircraftReport implements Serializable {
    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "taxsheet_sequence"
    )
    @SequenceGenerator(
            name = "taxsheet_sequence",
            allocationSize = 1
    )
    @Column(nullable = false, updatable = false)
    private Long id;
    ...

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "inbound_flight_id")
    private Flight inboundFlight;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "outbound_flight_id")
    private Flight outboundFlight;

    ...
}

【问题讨论】:

  • 为什么要使用mappedBy?

标签: java spring-boot hibernate jpa


【解决方案1】:

由于您有从 AircraftReport 到 Flight 的两个独立关系,因此您还必须将 Flight 到 AircraftReport 的关系分开。

@OneToOne(mappedBy = "inboundFlight")
private AircraftReport aircraftReportInbound;

@OneToOne(mappedBy = "outboundFlight")
private AircraftReport aircraftReportOutbound;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-15
    • 2019-06-21
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多