• Post Reply Bookmark Topic Watch Topic
  • New Topic

[JPA] Can I mark two fields with @Id annotation  RSS feed

 
Kalyana Sundaram
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any field or property that holds the persistent identity of the entity is annotated with @Id. Is it legal to mark two fields with @Id annotation if in case my requirement is to have two primary keys?

Thanks in Advance !!!
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know, JPA supports compount primary keys. So yes, you can have more than one @Id.
 
Mark Spritzler
ranger
Sheriff
Posts: 17309
11
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Usually when you have that model, you create a class that will store both properties and this will act as a Id Class, then you have your @Id on one property in the mapped class so

public class MyPK{

private Long someNumber;
private String someOtherField;

}

@Entity
public class AMappedClass{

@Id
private MyPK myId;
}

Or is it @EmbeddedId? I can't remember if @EmbeddedId is currently there, or if it is still in discussion by the JSR group for the next version of JPA.

Mark
 
Mike Keith
author
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JPA 1.0 currently supports two different approaches for compound PKs. In each case there must be a PK class that includes the fields.

1) Multiple @Id fields/attributes on the entity. Names and types of fields in the entity must match those in the PK class. Must also have an @IdClass annotation on the class. Ex:

public class EmpPK {
int id;
String name;
...
}

@Entity
@IdClass(EmpPK.class)
public class Employee {
@Id int id;
@Id String name;

...
}

2. Embed an attribute of the PK class in the entity. In this case the attribute is marked with @EmbeddedId and the PK class must be annotated with @Embeddable. Ex:

@Embeddable
public class EmpPK {
int id;
String name;
...
}

@Entity
public class Employee {
@EmbeddedId EmpPK empId;
...
}

Hope this helps.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!