我对三角形表格结构有疑问。参见 ER 图。
我在 JDBC 的帮助下用 Java 实现了这个。
车站等级:
@Table("station")
public class Station {
@Id
private Long id;
@Setter
@Getter
private String name;
@Setter
@Getter
private Double[] gps;
@Setter
@Getter
@MappedCollection(idColumn = "station_id")
private Set<Sensor> sensors = new HashSet<>();
@Setter
@Getter
@MappedCollection(idColumn = "station_id")
private Set<Measurement> measurementList = new HashSet<>();
}
传感器类别:
@Getter
@Table("sensor")
public class Sensor {
@Id
private Long id;
@Setter
private String type;
@Setter
private String name;
@Setter
private String sensor_unique;
@Setter
@Getter
@MappedCollection(idColumn = "sensor_id")
private Set<Measurement> measurementList = new HashSet<>();
}
测量等级:
@Getter
@Table("measurement")
public class Measurement {
@Id
private long id;
@Setter
private LocalDateTime measurement_datetime;
@Setter
private double value;
@Setter
private String unit;
}
我总是缺少测量表的外键之一。我怎样才能实现它以便保存两个外键。
我尝试将列表从站复制到传感器,但不允许。我没有进一步的想法,或者我的表格中有设计错误。
查看您传递的图表,如果您希望
measurement
表将 sensor
和 station
的 id 作为外键,只需使用一对一关系即可。
如果您知道你们的关系只会从
measurement
到 sensor
或 station
,您可以将其设置为单向。
@OneToOne
@JoinColumn(name = "station_id", referencedColumnName = "id")
private Station station
@OneToOne
@JoinColumn(name = "sensor_id", referencedColumnName = "id")
private Sensor sensor
您还可以通过使用
mappedBy
设置另一个实体来将其设置为双向一对一关系。例如,在 Station
类中,您可以添加:
@OneToOne(
// indicates that this is the child side of a
// relationship and refers to the field in the Driver
// class that defines the relationship there
mappedBy = "station")
private Measurement measurement;
我为您留下了不同可能关系的链接,以防您需要一对多/多对一或多对多关系:https://medium.com/@bdamianchamel/relationships-in -spring-data-jpa-7c5ceaf05f29