Lets say I have the following SQL table definitions:
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)
);
Furthermore I have two appropriate JPA mapping classes like this:
@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;
}
}
The intention is to have a single key generation in Table overview
and use that key for two things. First as foreign key in details
table and as primary key for overview
table as well.
One question is: Is this possible with Hibernate / Spring Data JPA? Based on what I have read it should be?
I have some test code which save things into overview
, details
tables but always fail with a error message like this:
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
Maybe someone has an idea what I'm doing wrong?