gpt4 book ai didi

java - Hibernate 复合键连接

转载 作者:行者123 更新时间:2023-12-02 12:22:18 25 4
gpt4 key购买 nike

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

最佳答案

Associations marked as mappedBy must not define database mappings like @JoinTable or @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
}

注意:您可以决定哪个是关系的所有者,并相应地放置您的映射,或者一个设备有多个设备设置,或者其他方式。

关于java - Hibernate 复合键连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45679576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com