我在 java/spring 中有以下问题。
我试图用一个更具体的案例来最大程度地简化我的问题。总而言之,我们有一个国家类,每个国家都与许多城市相关联。每个城市都通过一条中级道路与另一个城市相连。
我以这种方式实现了它(见下文),但这并不让我满意,因为我们在 Road 对象中有冗余,通过其城市和国家属性链接到 Country(例如,假设我们不关心复制品,即 Road Paris-Lyon 和 Road Lyon-Paris)。
另一个精度,我们没有跨国。国家下的所有道路和城市都属于同一个国家。
public class Country implements Serializable {
...
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "country")
private List<City> cities;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "country")
private List<Road> roads;
}
public class City implements Serializable {
...
@ManyToOne(optional = false)
@JoinColumn(name = "countryId", referencedColumnName = "id")
private Country country;
}
public class Road implements Serializable {
// Unicity by the corresponding 3 items countryId, cityFromId and cityToId
...
@ManyToOne(optional = false)
@JoinColumn(name = "countryId", referencedColumnName = "id")
private Country country;
@ManyToOne(optional = false)
@JoinColumn(name = "cityFromId", referencedColumnName = "id")
private City cityFrom;
@ManyToOne(optional = false)
@JoinColumn(name = "cityToId", referencedColumnName = "id")
private City cityTo;
}
为了避免这种重复引用,我们可以设想在 Road 类中取消对 Country 类的引用,但这意味着在类 City 中添加引用 @OneToMany 或 Road。由于这条道路连接了 2 个城市(见下文),因此我们将处于循环参考中。
public class Country implements Serializable {
...
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "country")
private List<City> cities;
}
public class City implements Serializable {
...
@ManyToOne(optional = false)
@JoinColumn(name = "countryId", referencedColumnName = "id")
private Country country;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "cityFrom")
private List<Road> cityFromRoad;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "cityTo")
private List<Road> cityToRoad;
}
public class Road implements Serializable {
// Unicity by the corresponding 3 items countryId, cityFromId and cityToId
...
@ManyToOne(optional = false)
@JoinColumn(name = "cityFromId", referencedColumnName = "id")
private City cityFrom;
@ManyToOne(optional = false)
@JoinColumn(name = "cityToId", referencedColumnName = "id")
private City cityTo;
}
你能帮我找到一个更好的方法来制作我的模型吗?
非常感谢!