我正在使用JPA和Hibernate 4.x.以及postgresql 9.x,但我想知道一些问题。
当使用@ElementCollection注释,并且我配置了Set type embedded字段时,我希望生成可嵌入Collection Table的主键,但它不起作用。我只能找到一个反对关系所有者的外键。我想知道它为什么不生成主键。这是我的测试代码。 A.java
@Entity
public class A {
@Id
private Long id;
@Column(name = "\"as\"")
private String as;
public String getAs() {
return as;
}
public void setAs(String as) {
this.as = as;
}
@ElementCollection
private Set<B> bs = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<B> getBs() {
return bs;
}
public void setBs(Set<B> bs) {
this.bs = bs;
}
}
B.java
@Embeddable
public class B {
private String col1;
private String col2;
public String getCol1() {
return col1;
}
public void setCol1(String col1) {
this.col1 = col1;
}
public String getCol2() {
return col2;
}
public void setCol2(String col2) {
this.col2 = col2;
}
}
结果是
Hibernate:
create table A (
id int8 not null,
"as" varchar(255),
primary key (id)
)
Hibernate:
create table A_bs (
A_id int8 not null,
col1 varchar(255),
col2 varchar(255)
)
Hibernate:
alter table A_bs
add constraint FK_rcecll1ao3brmwwnsep3iqq3p
foreign key (A_id)
references A
让我知道它为什么没有生成主键? 提前谢谢〜
答案 0 :(得分:1)
因为@ElementCollection
用于映射简单元素的集合,这与实体不同。他们唯一需要的是对Hibernate(列A_id
和外键(A_id) references A
)正确生成的拥有实体的引用。有关详细信息,请查看this post。
如果您确实需要可嵌入对象中的主键,请考虑将其设置为正确的实体。