Gourav Saklecha
Gourav Saklecha

Reputation: 363

Hibernate one-to-one mapping with subclass composite column

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

I want to do the following mapping using hibernate :-

        company {
          company_id int,
          company_name varchar,
          country varchar
        }

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

Company_id of company table should map with company_id of company_detail table so I have set following mapping in POJO

     In Company POJO :-
         @OneToOne(cascade=CascadeType.ALL)
         @JoinColumn(name="COMPANY_ID")  
         private CompanyDetails companyDetails;

        In CompanyDetails POJO :-
        @Column(name="COMPANY_ID", nullable=false)  
        public Company company;

Also, add following code in setter:-

public void setCompanyDetails(CompanyDetails companyDetails) {
        companyDetails.setCompany(this);
        this.companyDetails = companyDetails;
    }

This code working fine, Only one problem coming while saving the company, null is storing in company_id of company_detal instead of company id which is created in company table. All other details storing properly. So how to set one-to-one mapping in POJO for above table structure?

Upvotes: 2

Views: 197

Answers (1)

Sagar
Sagar

Reputation: 838

Edited :

if you want to generate separate primary key for CompanyDetail , then it is as simple as below

 @Id  
 @GeneratedValue  
 @Column(name="COMPANY_DETAIL_ID", unique = true, nullable = false) 
 public int companyDetailId;

 @OneToOne  
 @PrimaryKeyJoinColumn(name="COMPANY_ID")  
 public Company company;

######################################################################

Refer this link hibernate-jpa-onetoone-association-by-common-primary-ke

You must use a shared primary key generator in your companyDetail something like below

 @Id  
 @GeneratedValue(generator="SharedPrimaryKeyGenerator")  
 @GenericGenerator(name="SharedPrimaryKeyGenerator",strategy="foreign",parameters = @Parameter(name="property", value="company"))  
 @Column(name="COMPANY_ID", unique = true, nullable = false)  
 public int companyId;

 @OneToOne  
 @PrimaryKeyJoinColumn  
 public Company company;

And in you Company

  @OneToOne(cascade=CascadeType.ALL)  
  @PrimaryKeyJoinColumn(referencedColumnName="Company_ID")  
  public CompanyDetail companyDetail

Also make sure you set the company value CompanyDetail and companyDetail value in Company as below,

In Company

public void setCompanyDetail(CompanyDetail companyDetail){
   companyDetail.setCompany(this);
   this.companyDetail = companyDetail;
}

similarly in CompanyDetail

public void setCompany(Company company){
   company.setCompanyDetail(this);
   this.company = company;
}

Upvotes: 1

Related Questions