我有一个称为Flight的域类,它代表已经飞行的航班.我还有一个称为“运动”的类,它可以表示出发或到达,并包含日期和时间以及发生运动的机场.
@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;
}
但是,我不确定如何在Movement类中正确注释飞行场.我认为Flight类必须是关系的所有者,因为如果不是,则无法确定特定Flight的运动是出发还是到达:
@OneToOne
private Movement departure;
@OneToOne
private Movement arrival;
然而,这带来了问题.我无法在两个字段上的“运动”类中映射飞行字段:
// This obviously does not work
@OneToOne(mappedBy = "departure")
@OneToOne(mappedBy = "arrival")
private Flight flight;
我如何正确地对此进行注释,使出发和到达字段都正确引用运动,并且仍然能够使Movement类上的Flight字段引用Flight类?
解决方法:
如果您确实需要双向关系,则需要移动字段,其中之一始终为空:
@OneToOne(mappedBy = "departure")
private Flight departureFlight;
@OneToOne(mappedBy = "arrival")
private Flight arrivalFlight;
但是您可能只有一个吸气剂:
public Flight getFlight() {
return departureFlight == null ? arrivalFlight : departureFlight;
}
标签:jpa,java,java-ee
来源: https://codeday.me/bug/20191207/2087196.html