Mysql auto generated PK used for another table and JPA
Joined: Apr 24, 2004
My use case is as follows: I use MySQL and JPA 2 and I have two entities: Order and LineItem that are associated by a OneToMany relationship.
I would like for the GUI layer to persist the Order together with the LineItems at the same time (using the Order PK).
Bearing in mind that the PK of Order is auto-generated by MySQL and is part of the PK of LineItem, I don't know how to retrieve the generated Order PK in order to use it for the LineItem PK within the same transaction.
Is there any special JPA configuration I could use to achieve this?
Can anyone help please?
Joined: Oct 01, 2007
Well, you should need this id to persist the line items.
Just persist the Order that has its lineItems set to new LineItem and enable cascade persist on the relationship (or call persist on each line item).
As long as you set the ManyToOne back from LineItem to order, and map this as @Id, then it will just work.
I am actually realizing that my domain is a bit more complicated that what I described initially.
My domain is as follows: I have an Advertisement entity engaged in a many to many relationship with a TimeSlot entity with a join entity sitting in between the two entities: AdvertisementToTimeSlotToDayJoin. There is actually a third entity Day which I have omitted.
The only value that is not know in advance, as far as the constructor of AdvertisementToTimeSlotToDayJoinPK is concerned is the Avertisement PK, wich is autogenerated. How then can I persist my Avertisement together with its related join entities?
Do not map the foreign keys as Basic, just add @Id to the ManyToOnes.
Thanks for the reply.
Should I keep both classes:
I keep getting the following compilation error:
- There is no primary key attribute to match the ID class attribute timeslotID
Here are my entities after I modified according to your advice:
Joined: Apr 24, 2004
I am still struggling with my JPA entities.
Here is what I have tried:
In my Advertisement entity class:
Here is what I now get:
Exception Description: The @JoinColumns on the annotated element [field advertisementToTimeSlotToDayJoinCollection] from the entity class [class com.bignibou.domain.Advertisement] is incomplete. When the source entity class uses a composite primary key, a @JoinColumn must be specified for each join column using the @JoinColumns. Both the name and the referencedColumnName elements must be specified in each such @JoinColumn.