I have a domain class called Flight that represents a flight that has been flown. I have another class called Movement which can represents either a departure or an arrival and contains a date and time and the airport at which the movement occured.
@Entity
public class Flight implements Serializable {
private Movement departure;
private Movement arrival;
}
@Entity
public class Movement implements Serializable {
@Temporal(TemporalType.TIMESTAMP)
private Date dateTime;
@ManyToOne
private Airport airport;
private Flight flight;
}
I am however not sure how to properly annotate the flight field in the Movement class. I figured the Flight class has to be the owning side of the relationship because if it is not, there is no way to tell if the Movement of a specific Flight was the departure or the arrival:
@OneToOne
private Movement departure;
@OneToOne
private Movement arrival;
This, however, poses a problem. I can’t map the flight field in the Movement class on both fields:
// This obviously does not work
@OneToOne(mappedBy = "departure")
@OneToOne(mappedBy = "arrival")
private Flight flight;
How would I go about properly annotating this, having both the departure and arrival field properly reference the Movement and still be able to have the flight field on the Movement class reference the Flight class?
If you really need a bidirectional relationship, then you’ll need to have to fields in movement, with one of them always being null:
But you could have a single getter: