如何将表映射到对象属性?

时间:2019-05-06 20:50:28

标签: spring spring-boot spring-data-jpa

我的设备上有许多相同的传感器,因此我需要根据需要映射尽可能多的实体属性,而不是为每个传感器设计一个表。

如何在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
    .
    .
    .


1 个答案:

答案 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将充当其他两个表之间的链接。