JPA, Hibernate: OneToOne mapping with foreign key only

Stupidfrog picture Stupidfrog · Aug 19, 2014 · Viewed 8k times · Source

Environment:

  • Hibernate 4.1.6.final
  • Spring 3.1.2.release
  • Spring JPA 1.1.0.release
  • PostgreSQL 9.1-901-1.jdbc4

I decided to rephrase the questions.

There are 2 tables:

public company
{
  private Long id;
  private Long name;
  private address table_address;
}
public address
{
  private Long id;
  private String address;
  private Long company_id;
}

Note: both table id is sequential and no related. Except table.address.company_id is foreign key of company.

how to do mapping? what result i expected is:

"company":{
            "id":4,
            "name":"company name",
            "address":{
                         "id":3,
                         "address":"anywhere",
                         "company_id":4
                      }
          }

So can somebody teach me that, how to map this 2 table?

Answer

Abhishek Nayak picture Abhishek Nayak · Aug 19, 2014

what you want is One-to-One mapping between Company and Address

just add @OneToOne annotation to table_address field of Company class:

 public class Address {

        @Id
        @GeneratedValue
        private Long id;
        private String address;
        @OneToOne
        @PrimaryKeyJoinColumn
        private Company company;

        //getters and setters
    }

public class Company {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToOne(mappedBy = "company",cascade = CascadeType.ALL)
    private Address companyAddress;

    //getters and setters
}

Apart from the problem: respect java naming convention, in your case class name should start with capital letter and the next word in the variable name too. i.e. company should be Company and address should be Address, private address table_address; change to private Address companyAddress;

Updated solution

public class Address {

    @Id
    @GeneratedValue
    private Long id;
    private String address;
    @OneToOne
    @JoinColumn(name = "company_id")
    private Company company;

    //getters and setters
}

public class Company {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToOne(mappedBy = "company",cascade = CascadeType.ALL)
    private Address companyAddress;

    //getters and setters
}

from stupidfrog: if u using @PrimaryKeyJoinColumn, then the id join wrong. the id join with both primary but not address table company_id

here is the reference from hibernate http://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/OneToOne.html the example 1