这是我的场景,我试图通过OneToMany关系使用@JoinColumn
将实体B与实体A关联,其中列a1,a2,a3和i得到错误referenced column names not mapped to a single property
。后来我在表A上尝试了@Uniqueconstraint
a1,a2和a3列,但我无法成功。你们中的任何人可以帮助我将实体B与A关联为@OnToMany关系吗?
A
--
a1
a2
a3
PrimaryKey -- a1 and a2
B
--
a1
a2
a3
b1
b2
PrimaryKey -- a1, a2, a3, and b1
@Entity
@Table(name = "A")
Class A
{
@EmbeddedId
private APK apk;
@Column(name="a3")
private Integer a3;
@OneToMany(mappedBy="a")
private Set<B> bSet;
}
@Embeddable
Class APK
{
@Column(name="a1")
private Integer a1;
@Column(name="a2")
private Integer a2;
}
@Entity
@Table(name = "B")
Class B
{
@EmbeddedId
private BPK bpk;
@Column(name="b2")
private Integer b2;
@ManyToOne
@JoinColumns({
@JoinColumn(name="a1", referencedColumnName="a1", insertable=false, updatable=false),
@JoinColumn(name="a2", referencedColumnName="a2", insertable=false, updatable=false),
@JoinColumn(name="a3", referencedColumnName="a3", insertable=false, updatable=false)
})
private A a;
}
@Embeddable
Class BPK
{
@Column(name="a1")
private Integer a1;
@Column(name="a2")
private Integer a2;
@Column(name="a3")
private Integer a2;
@Column(name="b1")
private Integer b1;
}
答案 0 :(得分:0)
a3不是A主键的一部分,所以不应该在B表中使用。
有几种方法可以映射它,但如果使用JPA 2.1,我会使用:
@Entity
@Table(name = "A")
Class A
{
@EmbeddedId
private APK apk;
@Column(name="a3")
private Integer a3;
@OneToMany(mappedby='a')
List bList;
}
@Embeddable
Class APK
{
@Column(name="a1")
private Integer a1;
@Column(name="a2")
private Integer a2;
}
@Entity
@IdClass(BPK.class)
@Table(name = "B")
Class B
{
@Id
@Column(name="b1")
private Integer b1;
@Column(name="b2")
private Integer b2;
@Id
@ManyToOne
@JoinColumns({
@JoinColumn(name="a1", referencedColumnName="a1"),
@JoinColumn(name="a2", referencedColumnName="a2")
})
private A a;
}
@Embeddable
Class BPK
{
private APK a;
private Integer b1;
}
虽然有许多方法可以映射它。