• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JPA: how to model compound key which contains also a foreign key?

 
Vincenzo Turco
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi developers,
I would like to have some piece of advice by you gurus about a modelling problem I am currently experiencing

in my (simplified) JPA scenario I have:
Building entity (identified by an id)
Room entity (identified by number, floor and building)
Of course both Room and Building have other info fields.

A coleague of mine proposed to
- create a RoomPK class containing: number, floor, buildingId (only the integer id not the full object)
- declare RoomPK @Embeddable
- declare an @EmbeddedId RoomPK instance variable in Room

I argued this completely violates JPA ORM.
I suggested that in Room entity we
- create a @Id auto-generated dummy id column (just for db use)
- model the relationship Room->Building as @ManyToOne
- use UniqueConstraint:number,floor, building

Is this correct? Is there a cleaner design?
Thanks so much for your opinion

Vincenzo



 
James Sutherland
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can define either with JPA. You could also to not make RoomPK Embeddable, or use the ManyToOne to Building as part of the Id and avoid the duplicate buildingId.

Personally I would agree with you, and use the generated Id in Room, it will make things much simpler.
 
Vincenzo Turco
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James Sutherland wrote: use the ManyToOne to Building as part of the Id and avoid the duplicate buildingId.

hi, thanks for replying!
that is exactly what I would like to do... but the only way I found is using uniqueconstraint.
Which other solution would you use?

Thanks again, regards
Vincenzo
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic