所以我有两个类,一个是Route,一个是BusStop。路线'使用'两个BusStop对象,一个作为开始,一个作为目标。我需要通过连接表映射这种关系,'使用'。
此联接表不需要区分BusStop是用于起点还是目的地。基本上我只需要在这个连接表中使用start和destination成为一个列(允许重复),这样我就可以得到一个完整的映射,显示哪些路由停止使用。
以下是我设置的方法(假设有吸气剂和固定剂):
public class Route {
@Id
private String number;
@Column(nullable = false)
private int frequency;
@ManyToOne
@JoinTable(
name = "Uses",
joinColumns = @JoinColumn(name = "number"),
inverseJoinColumns = @JoinColumn(name = "id")
)
private BusStop start;
@ManyToOne
@JoinTable(
name = "Uses",
joinColumns = @JoinColumn(name = "number"),
inverseJoinColumns = @JoinColumn(name = "id")
)
private BusStop destination;
...
}
public class BusStop {
@Id
private int id;
@Column(nullable = false)
private String description;
@OneToMany
@JoinTable(
name = "Uses",
joinColumns = @JoinColumn(name = "id"),
inverseJoinColumns = @JoinColumn(name = "number")
)
private Set<Route> routes;
...
}
现在我遇到的问题是,这导致了“使用”问题。只有每个Route id之一的表,尽管它成功地保留了重复的stop id。我假设它与我有关,试图创造两个用途&#39; Route类中的表?
那么究竟如何正确地解决这个问题呢?
答案 0 :(得分:1)
我会采用更清洁的方式来做到这一点。
这是我的实体。
package com.ansh.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Table(name = "routes")
@Getter @Setter
public class Route {
@Id
@Column(name = "number")
private String number;
@Column(name = "frequency", nullable = false)
private int frequency;
@ManyToOne
@JoinColumn(name = "start_id")
private BusStop start;
@ManyToOne
@JoinColumn(name = "destination_id")
private BusStop destination;
}
AND
package com.ansh.entity;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "bus_stops")
@Getter @Setter
public class BusStop {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "description", nullable = false)
private String description;
@OneToMany(mappedBy = "start")
private Set<Route> outgoingRoutes = Sets.newHashSet();
@OneToMany(mappedBy = "destination")
private Set<Route> incomingRoutes = Sets.newHashSet();
public Set<Route> getRoutes() {
return Sets.union(outgoingRoutes, incomingRoutes);
}
}