This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to assigned auto-generated PK to its FK - Please suggest

 
Manju Singh
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have 2 table HOSPITAL and PATIENT with one-to-many relation. hospital_id is PK on HOSPITAL which is auto-increment and same hospital_id is FK on PATIENT. So, while inserting hospital object I want the auto-generated hospital_id from HOSPITAL should be inserted into PATIENT into one save.

I have defined one-to-many relation in both mapping file.

I am populating patient object as
patient.setHospitalID(hospital.getHospitalID()); // I am not sure whether this is correct way to do, 'coz its auto increment

But, its inserting zero and I beleieve call to hospital.getHospitalID() will not give auto-increment number because it will be generated by DB at the time of insert.

This is URGENT, please let me know how to assigned same auto-generated PK to its FK
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I remember correctly, you don't need to set the hospital id in the child. Hibernate will do that for you.
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you do not need to set the hospital ID but the Hospital Object to Patient.

pascal
 
Manju Singh
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply. I posted same question to hibernate forum and got the reply as was same some what pascal replied.

Reply from Hibernate Forum
------------------------------------------------------------------
In your patient you'll want a many-to-one relationship back to hospital, and then before you save, set the hospital object in the patient.



<many-to-one
name="hospital"
class="package.Hospital"
not-null="true"
>
<column name="foreignkey_column_name" />
</many-to-one>


patient.setHospital(hospital);
----------------------------------------------------
I was missing this line of code - patient.setHospital(hospital);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic