• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to use a composite primary key as foreign key

 
Syed Khurram Anwar
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:




 
James Sutherland
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.
 
Martin Lopez Ochoteco
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?

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic