Harmeet Singh Taara
Harmeet Singh Taara

Reputation: 6611

JPA 2: how to declare primary-key columns in @ElementCollection tables

in JPA2 when we are using Embed-able (Basic Type like String.. etc ) object in Entity using with @ElementCollection and @CollectionTable annotation , the new table is created , but in new table how to declare primary-key contraint in column ? following is my code

public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name; 
private String salary;
@Transient
private String phnNum;
@Enumerated(EnumType.STRING)
private EmployeeType type;

@ElementCollection
@CollectionTable(name="vacations" , joinColumns=@JoinColumn(name="Emp_Id"))
private Collection<Vacation> vacationBooking;

@ElementCollection
private Set<String> nickNames;

    ...................

with this code the "vacation" and "employee_nickname" two tables are created in schema. but i want to declare the one primary-key column in both table . what i do for this?

Upvotes: 3

Views: 2183

Answers (2)

chaserb
chaserb

Reputation: 1456

It looks like a primary key per se is not supported by JPA 2.0:

From Wikibooks:

The JPA 2.0 specification does not provide a way to define the Id in the Embeddable. However, to delete or update an element of the ElementCollection mapping, some unique key is normally required. Otherwise, on every update the JPA provider would need to delete everything from the CollectionTable for the Entity, and then insert the values back. So, the JPA provider will most likely assume that the combination of all of the fields in the Embeddable are unique, in combination with the foreign key (JoinColumn(s)). This however could be inefficient, or just not feasible if the Embeddable is big, or complex.

Some JPA providers may allow the Id to be specified in the Embeddable, to resolve this issue. Note in this case the Id only needs to be unique for the collection, not the table, as the foreign key is included. Some may also allow the unique option on the CollectionTable to be used for this. Otherwise, if your Embeddable is complex, you may consider making it an Entity and use a OneToMany instead.

Upvotes: 1

Biman Tripathy
Biman Tripathy

Reputation: 2856

Do you mean that you want to assign 'id' from Employee table as foreign key to the Vacation table? In that case, you should use @OneToMany instead of @ElementCollection

Upvotes: 0

Related Questions