Reputation: 41
I am using JPA with Hibernate 4.x., and postgresql 9.x, but I wonder some problem.
When using @ElementCollection annotation, and I configured Set type embedded field, I expect to generate Primary key of embeddable Collection Table, but it's not working. I can find just one foreign key against owner of relationship. i wonder why do not it generate primary key. This is my test code. 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;
}
}
the result is
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
Let me know why it did not generate primary key? Thanks in advance~
Upvotes: 2
Views: 3758
Reputation: 56
To generate a primary key for an embeddable collection like Set need to mark all columns of embeddable class with annotation @Column(nullable = false)
, due to requirement that nullable fields could not be a part of composite primary key
Upvotes: 0
Reputation: 24423
Because @ElementCollection
is used for mapping collections of simple elements, which is not the same as entities. The only thing they need is a reference to owning entity which is properly generated by Hibernate (column A_id
and foreign key (A_id) references A
). Take a look at this post for more information.
If you really need a primary key in the embeddable object, consider making it a proper entity.
Upvotes: 1