JPA将组合外键的一部分作为主键的一部分



我在看所有可能的谷歌搜索和Stackoverflow搜索,但找不到我要找的东西。我的问题是,有一个类a和一个类B,类a有一个复合主键,类B有一个原始主键。这些类(表)与一个名为C的类连接,我需要这个,因为有其他数据与连接(底部的示例)。在类C中,我显然有类B和A的主键作为外键,但我需要类B的复合键和A的外键的第一个属性作为类C中的主键。

仅仅通过文本来理解它有点困难所以这里有一个例子:

public class CompositeId implements Serializable {
private Long id;
private Long version;
// Other stuff...
}
@Entity
@IdClass(CompositeId.class)
public class A {
@Id
private Long id;
@Id
private Long version;
private String name;
private String creatorName;
// Other stuff...
}
@Entity
public class B {
private Long id;
private String name;
// Othet stuff...
}
public class CompositeJoinId implements Serializable {
private Long aId; // Should equal to aReference's id property.
private Long bId; // Should equal to bReference's id property.
// Other stuff...
}
@IdClass(CompositeJoinId.class)
@Entity
public class C {
@Id
@ManyToOne
@JoinColumns({
@JoinColumn(name="a_id", referencedColumnName="id"),
@JoinColumn(name="a_version", referencedColumnName="version")
})
private A aReference;
@Id
@ManyToOne
@JoinColumn(name = "b_id")
private B bReference;
private Long day;
// Other stuff...
}

有办法让这发生吗?我所有的发现都只使用了一个类,其中使用了两个外组合键,但我只需要/想要一个。

我不太确定我理解你的问题;但我会像这样映射你的类(主要区别是CompositeJoinId):

public class CompositeId implements Serializable {
private Long id;
private Long version;
// Other stuff...
}
@Entity
@IdClass(CompositeId.class)
public class A {
@Id
private Long id;
@Id
private Long version;
private String name;
private String creatorName;
// Other stuff...
}
@Entity
public class B {
@Id
private Long id;
private String name;
// Othet stuff...
}
public class CompositeJoinId implements Serializable {
private Long aId;
private Long bReference; // matches name of @Id attribute and type of B PK
// Other stuff...
}
@IdClass(CompositeJoinId.class)
@Entity
public class C {
@Id
@Column(name = "a_id", insertable = false, updatable = false)
Long aId;
@Id
@ManyToOne
@JoinColumn(name = "b_id")
private B bReference;
@ManyToOne
@JoinColumns({
@JoinColumn(name="a_id", referencedColumnName="id"),
@JoinColumn(name="a_version", referencedColumnName="version")
})
private A aReference;
private Long day;
// Other stuff...
}

这些是派生恒等式的例子;和派生标识将在JPA 2.2规范的2.4.1节中讨论(带有示例)。

最新更新