我的设备上有许多相同的传感器,因此我需要根据需要映射尽可能多的实体属性,而不是为每个传感器设计一个表。
如何在Spring Boot中做到这一点?
赞:
@Entity
@Table(name = "device")
public class Devide {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Table(name = "sensor")
private Sensor sensor1; // This is my conceptual problem
@Table(name = "sensor")
private Sensor sensor2; // This is my conceptual problem
.
.
.
答案 0 :(得分:0)
由于您的一台设备可以有多个传感器,而一个Sensor可以作为可能的设备的一部分,因此您必须在Sensors和Devices之间创建ManyToMany关系。您可以参考以下映射
@Entity
@Table(name = "Device")
public class Device {
// ...
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "Device_Sensor",
joinColumns = { @JoinColumn(name = "Device_id") },
inverseJoinColumns = { @JoinColumn(name = "Sensor_id") }
)
Set<Sensor> Sensors = new HashSet<>();
// standard constructor/getters/setters
}
@Entity
@Table(name = "Sensor")
public class Sensor {
// ...
@ManyToMany(mappedBy = "Sensors")
private Set<Device> Devices = new HashSet<>();
// standard constructors/getters/setters
}
Device_Sensor将充当其他两个表之间的链接。