Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hibernate problem: One-To-Many association

 
Eduards Sizovs
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there!

I have a problem with Hibernate:
- Two classes - Company and CompanyContact have One-To-Many relation. When persisting a Company with some Contacts set, Hibernate generates
INSERT statement which does not have FOREIGN KEY set in Contacts. Unfortunately, I cannot spot why and hope for Your assistance,

Mapping for CompanyContact



Mapping for Company



SQL



Thank you,
 
Rahul Babbar
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your companycontact hbm should have a relationship to Company hbm,
like


and your CompanyContact Pojo should have a
private Company company;
and getters and setters for it.
 
Eduards Sizovs
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for response,

In this case, it requires manual setting of CompanyID property, otherwise it inserts null.

Is it possible for Hibernate to determine Foreign Key for associated entities from their parent?
 
Rahul Babbar
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will set companyId as null in the CompanyContact table if any of the following holds true.
1. One do not have an assocation, but only have a column in the CompanyContact and never sets that property.
2. If one has an association, but is not doing something like "companyContact.setCompany(contact);"
3. If one has both an association as well as setting the company in companyContact as above, but one is not setting the companyId in company and the id generation in Company hbm is defined as "assigned".
 
Rahul Babbar
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Eduards Sizovs wrote:
Is it possible for Hibernate to determine Foreign Key for associated entities from their parent?


I dont think so,
since the foreign key exists in the child table and not in the parent table, you need to have the association in the child hbm atleast(which was missing from your original set of hbms)
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic