You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为同一类的两个字段配置@OneToOne一对一映射关系

正确定义Flight与AircraftReport的双向@OneToOne关系

你当前的问题在于:AircraftReport里有两个指向Flight的一对一关联(进港、出港航班),但Flight中仅定义了一个aircraftReport字段,这不符合双向关联的逻辑——一个航班既可能作为某份报告的进港航班,也可能作为另一份报告的出港航班,因此需要在Flight中分别定义两个反向关联字段来对应这两种场景。

修改后的Flight类代码

@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;

    // 作为进港航班对应的AircraftReport反向关联
    @OneToOne(mappedBy = "inboundFlight")
    private AircraftReport inboundAircraftReport;

    // 作为出港航班对应的AircraftReport反向关联
    @OneToOne(mappedBy = "outboundFlight")
    private AircraftReport outboundAircraftReport;
}

优化后的AircraftReport类代码(可选)

如果需要在数据库层面保证一对一的唯一性(即一个航班不能同时被多份报告标记为进港/出港航班),可以在@JoinColumn中添加unique=true约束:

@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", unique = true)
    private Flight inboundFlight;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "outbound_flight_id", unique = true)
    private Flight outboundFlight;

    ...
}

关键说明

  1. 双向一对一关联中,mappedBy的值必须对应另一方实体中定义的关联字段名,因此Flight的两个反向字段分别映射到AircraftReport的inboundFlight和outboundFlight。
  2. unique=true是为了强化一对一关系的语义,避免同一个航班被多份报告重复关联。
  3. 如果不需要从Flight端反向查询对应的AircraftReport,可以直接删除Flight中的关联字段,仅保留AircraftReport中的单向关联即可。

内容的提问来源于stack exchange,提问作者GoingAround

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 22:25:23