我正在尝试使用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
}


注意:您可以确定关系的所有者,然后根据自己的意愿放置映射,即“一台设备”具有许多设备设置或采用其他方法。

09-25 21:43