• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 !!!
 
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As far as I know, JPA supports compount primary keys. So yes, you can have more than one @Id.
 
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 304
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic