假设我有以下SQL表定义:
create table overview (
key bigserial not null,
supplemental decimal(20) not null,
constraint overview_pk primary key (key)
);
create table details (
key decimal(20) not null,
ver decimal(20) not null,
constraint details_pk primary key (key, ver)
);
此外,我有两个适当的JPA映射类,如下所示:
@Entity
@Table(name = "overview")
public class Overview implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "key", unique = true, nullable = false)
private BigDecimal key;
@Column(nullable = false)
private BigDecimal supplemental;
@OneToOne(mappedBy = "overview")
private Details details;
public Overview() {
}
public Overview(BigDecimal supplemental, Details details) {
this.details = details;
this.details.setOverview(this);
}
@Entity
@Table(name = "details")
public class Details implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "key", nullable = false)
protected BigDecimal key;
@Column(name = "ver", nullable = false)
protected BigDecimal ver;
@OneToOne(fetch = FetchType.LAZY)
@MapsId(value = "key")
private Overview overview;
public Details() {
}
public Overview getOverview() {
return overview;
}
public void setOverview(Overview overview) {
this.overview = overview;
}
}
目的是在表overview
中生成单个密钥,并将该密钥用于两个方面。首先是details
表中的外键,也是overview
表的主键。
一个问题是:Hibernate / Spring Data JPA可以实现吗? Based on what I have read it should be?
我有一些测试代码可以将内容保存到overview
,details
表中,但总是失败并显示如下错误消息:
nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException:
object references an unsaved transient instance - save the transient instance before flushing
: xyz.modell.Overview.details
-> xyz.modell.Details
也许有人知道我做错了什么?