开发者

Bidirectional one-to-one mapped to multiple fields

开发者 https://www.devze.com 2023-04-09 17:12 出处:网络
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 tim

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 pro开发者_JAVA百科perly 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:

@OneToOne(mappedBy = "departure")
private Flight departureFlight;

@OneToOne(mappedBy = "arrival")
private Flight arrivalFlight;

But you could have a single getter:

public Flight getFlight() {
    return departureFlight == null ? arrivalFlight : departureFlight;
}


If you need two way relationship, you could change relation type to @ManyToMany, so you could use a join table with additional status column. There you'd specify whether it's an arrival or departure.

Wikibooks provide an example how to map it. This kind of relation, though, is quite cumbersome to handle in code.

Or maybe you don't need a two way relationship at all, as glowcoder suggests? It would be much simpler to map, use, and faster to run.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号