Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

@PrimaryKeyJoinColumn with bidirectional @OneToOne relationship

 
Johnny Cheng
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two objects Mat and MatImage, parent and child resp. The primary key of MatImage is the id of Mat and they are join by one to one relationship.

If I understand bidirectional relation correctly, the child object would know about the parent if I do something like matImage.setMat(mat). I would think the primary key would be filled at this point, but it doesn't. I know this because sql throws an exception when it try to insert MatImage with #0 as matId.

Another question is with the n+1 problem. I would like to lazily load child object because not all mat has matimage. I can try changing @OneToOne to @ManyToOne but not sure how that can be done bidirectionally. Any help would be appreciated. Thank you.

Here are the entities:




 
James Sutherland
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See,

http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_Relationships

Basically you need to set the MatImage matId in your setMat method to keep it in synch. In JPA 2.0 it is much easier, you don't need to matId, you just need to add @Id to the @OneToOne mapping.

The @PrimaryKeyJoinColumn needs to be on the MatImage not the Mat, the Mat has a mappedBy, so any join column is ignored.

The matImage cannot be optional, as this is part of its Id.

Not sure what you mean for n+1, you can make OneToOne lazy the same as ManyToOne. Ensure you are enabling weaving/agent.

You can also use join fetching, see,
http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Join_Fetching
 
Johnny Cheng
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your reply. I corrected the mapping by putting @PrimaryKeyColumn in owned entity and Removed @JoinColumn when mapped by is used. I guess I am still confused with the benefit of using PrimaryKeyJoinColumn annotation since I still have to set matId in MatImage. I was hoping to do something like



And expects the matId in matImage to be populated because matId is id in Mat object. Am I missing something? Thank you.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic