簡體   English   中英

休眠復合鍵聯接

[英]Hibernate Composite Key Join

我正在嘗試使用Spring Data執行聯接的查詢,但是我的一個表具有復合鍵,並且不確定如何映射實體。

這是數據模型的一個類比:

table: device
pk=model_id
pk=serial_id
...

table: device_settings
pk=device_settings_id
fk=model_id
fk=serial_id
...

這是一個類似的代碼,由於不存在“ mappedby”屬性而無法編譯。

@Entity
@Table(name = "device_settings")
public class DeviceSettings {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "device_settings_id")
    private Long id;

    // Pretty sure this is the problem
    @OneToMany(targetEntity = Device.class, mappedBy = "deviceKey", cascade = {CascadeType.MERGE}, fetch = FetchType.EAGER)
    @JoinColumns({
        @JoinColumn(name = "model_id", referencedColumnName = "model_id"),
        @JoinColumn(name = "serial_id", referencedColumnName = "serial_id")})
    private List<Device> devices;
}

@Entity
@Table(name = "device")
public class Device {
    @Id
        private DeviceKey deviceKey;
    }
    ...
}


@Embeddable
public class DeviceKey implements Serializable {
    private static final long serialVersionUID = -1943684511893963184L;

    @Column(name = "model_id")
    private Long modelId;

    @Column(name = "serial_id")
    private Short serialId;
}

標記為mappingBy的關聯不得定義@JoinTable或@JoinColumn之類的數據庫映射

要實現您的方案,您必須定義@ManyToOne:

@ManyToOne(cascade = {CascadeType.MERGE}, fetch = FetchType.EAGER)
    @JoinColumns({
        @JoinColumn(name = "model_id", referencedColumnName = "model_id"),
        @JoinColumn(name = "serial_id", referencedColumnName = "serial_id")})
     private Device device;

這將最終成為model_id,serial_id,device_settings_id

要么

在設備實體實體中定義@JoinColumn:

設備設置

    @Entity
    @Table(name = "device_settings")
    public class DeviceSettings {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "device_settings_id")
        private Long id;


        @OneToMany( mappedBy = "deviceSettings", cascade = {CascadeType.MERGE}, fetch = FetchType.EAGER)
         private List<Device> devices;
}

設備實體

@Entity
@Table(name = "device")
public class Device {

        @EmbeddedId
        private DeviceKey deviceKey;

        @ManyToOne
        @JoinColumn(name="device_settings_id")
        private DeviceSettings deviceSettings;
       //getters and setters
}

注意:您可以確定關系的所有者,然后根據自己的意願放置映射,即“一台設備”具有許多設備設置,也可以采用其他方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM