[英]JPA @Id on @OneToOne Entity with a Composite Key
我有一个@Entity
类,在同一个字段上有一个@Id
注释和一个@OneToOne
注释。 通常这不会有问题,但是带有这些注释的字段的实体类使用复合键。 这导致的并发症比我预期的要多。
这是造成问题的实体类:
@Entity
public class ReportDetails implements Serializable {
@Id
@OneToOne
private MachineLine machineLine;
}
这是在ReportDetails
用作 ID 的MachineLine
实体类:
@Entity
@IdClass(MachineLine.MachineLineKey.class)
public class MachineLine {
@Id
@ManyToOne
private Machine machine;
@Id
private long lineIndex;
public static class MachineLineKey implements Serializable {
private Machine machine;
private long lineIndex;
}
}
为了节省空间,我从这些类定义中省略了任何额外的字段以及 getter 和 setter。
当我尝试运行我的应用程序时,它给出了以下异常:
java.lang.IllegalArgumentException: This class [class ReportDetails] does not define an IdClass
当我在ReportDetails
上添加@IdClass
注释时,它需要定义我在@IdClass
定义的任何类的各个字段,就像在MachineLine
。 但是,我试图避免这样做,以便在从数据库中检索ReportDetails
实体时返回整个MachineLine
实体。
有没有办法让MachineLine
作为ReportDetails
的 ID 字段,而不必在ReportDetails
定义额外的字段?
这就是 JPA 所说的“派生身份”。 你可以尝试这样的事情:
报告详情:
@Entity
public class ReportDetails implements Serializable {
// all attributes map by the relationship: AttributeOverride is not allowed
@EmbeddedId
private MachineLine.Id id;
@MapsId
@JoinColumns({
@JoinColumn(name="machineId", referencedColumnName="machineId"),
@JoinColumn(name="machineLineIndex", referencedColumnName="index")
})
@OneToOne
private MachineLine machineLine;
// ...
}
机器线:
@Entity
public class MachineLine {
@EmbeddedId
private Id id;
@MapsId("machineId") // maps machineId attribute of embedded id
@ManyToOne
private Machine machine;
// ...
@Embeddable
public static class Id implements Serializable {
private long machineId; // corresponds to PK type of Machine
private long index;
// ...
}
}
机器:
@Entity
public class Machine {
@Id
private long id;
@OneToMany(mappedBy = "machine")
private List<MachineLine> lines;
// ...
}
派生身份在JPA 2.2 规范的 2.4.1 节中讨论(通过示例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.