Hibernate Composite Key Join

时间:2017-08-14 17:09:34

标签: java spring hibernate

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

1 个答案:

答案 0 :(得分:1)

  

标记为mappedBy的关联不得定义数据库映射,如@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 实体:

DeviceSettings

    @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
}

注意:您可以决定哪个是该关系的所有者,并按照一台设备有多种设备设置或其他方式来定位您的映射。