This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Svelte and Sapper in Action and have Mark Volkmann on-line!
See this thread for details.
Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

how to use a composite primary key as foreign key

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
  • 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
  • Quote
  • Report post to moderator
How to use it in the following class as foreign key?

 
Time is the best teacher, but unfortunately, it kills all of its students - Robin Williams. tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic