• 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

how to use a composite primary key as foreign key

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a class HardwareConfiguration which contains a composite primary key. I have done that using JPA Annotations. Here is the code:



Here is the class for composite primary key:



Now I want to use this composite primary key as a foreign key in another class. How can I do that using annotations. here is the class which is using this composite key as foreign key:




 
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You should not need to do anything, as the hardwareConfiguration will be defaulted to a OneToOne using a foreign key to both Id fields.
You could annotate it as a @OneToOne, and include a @JoinColumn for each foreign key column to the HardwareConfiguration (id and version).

Note that your annotations for HardwareConfiguration are not correct, they should use @EmbeddedId not @Id.

 
Syed Khurram Anwar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks. I am new to Hibernate. Would you please tell me the syntax that how will I use this key in another class as foreign key?

I read the book "Hibernate Made Easy" by Cameron. He has explained 3 ways to use embeddable class

1 - @id

2 - @IdClass

3 - @EmbeddedId

I have used the first one.
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think @EmbeddedId is the best approach. @IdClass is only declared in JPAs new specification because of EJB2 compatibility.

Code:
 
Syed Khurram Anwar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How to use it in the following class as foreign key?

 
reply
    Bookmark Topic Watch Topic
  • New Topic