Home > other >  Mapping two fields of the same class with One-to-One relationship
Mapping two fields of the same class with One-to-One relationship

Time:12-13

I have a Flight class and a AircraftReport class. The AircraftReport class contains an inbound flight and an outbound flight which I would both like to be mapped as a @OneToOne. How do I correctly define the relationship?

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

    ...
}

CodePudding user response:

As you have two separate relationships from AircraftReport to Flight, you also have to separate relationships from Flight to AircraftReport.

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

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

CodePudding user response:

IMHO you don't need to use a bidirectional relationship for a OneToOne mapping. If you want the AircraftReport just get the AircraftReport and the Flight instance will come with it. Otherwise if you're not working with a report just get the Flight and be happy.

Also, I don't recommend using Cascade operations on a OneToOne, or at any time for that matter. Do you really ever want the Flight deleted?

Map to either inboundFlight or outboundFlight. You can't have one bidirectional relationship take the place of two of them. If you want two bidirectional relationships then add another to Flight.

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

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