OK, I’ve tried everything, just can’t make this to work:
I have the following table:
- user_id int , references users.id
- platform_id int , references platforms.id
- field1
- field2
- …
My primary key (in th DB and logically) is the combination of user_id and platform_id.
I want to create a composite key that will have the User and Platform classes as members (like I would do with a regular OneToOne or OneToMany relations).
I want the composite key to have the actual classes references and not only the ids (much easier for me later when I need the actual reference for some calculations).
Furthermore, I need the User class to have a OneToMany relation with this UserPlatformData class.
I was able to create an Embeddable class with User and Platform but JPA always does insert and never updates the existing records even when the pk is the same (that leads to duplicate entry for key primary...).
How do I create a class with a primary key that consists of two other references (not primitives)?
Declare your entity, using the @IdClass annotation and two @Id annotations. There are two options for the id field types:
(i) basic types: matching the DB columns OR
(ii) non-basic types: entity objects referenced as @ManyToOne via a FK, allowing FK relationships to be part of the PK.
You have said you want this second case:
Declare a javabean id class to describe the composite PK fields.
The @IdClass thus acts as a form of mapping from non-basic types in the entity to basic types in the DB:
You can leave out setter methods, and instead have an extra constructor to set fields up front. Once created, the Id should be immutable.
Good to go =:-)