Gourav Saklecha Gourav Saklecha - 13 days ago 6
Java Question

Hibernate One-to-One Mapping not fetching child class data with parent class

I have two tables, 1'st table contains company_id, company_name and country name and second table contain company related detail with one to one mapping.

This is my table structure :-

company {
company_id int,
company_name varchar,
country varchar
}

company_detail {
id int,
company_id int,
company_description text,
future_goal text
}


Following mapping used in POJO :-

In Company POJO :-

@OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="COMPANY_ID")
private CompanyDetails companyDetails;


In CompanyDetail POJO :-

@OneToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="COMPANY_ID")
public Company company;


But when I get company object its contain null in companyDetails.

Following code used to get Company Object :-

Company company = (Company) session.get(Company.class, companyId);


I want to get companyDetails data together with company data.

am I doing something wrong?
What Code changes required to fix this problem.

Answer

Use the bidirectional @OneToOne relationships (read more info about it):

// in Company POJO:
@OneToOne(mappedBy="company", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private CompanyDetails companyDetails

// in CompanyDetails POJO:
@OneToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="company_id")  
public Company company;

Then after fetching the company object, you can get it's details (as Company has CompanyDetails filed):

Company company = (Company) session.get(Company.class, companyId);
CompanyDetails details = company.getCompanyDetails();