0

Which is general and better approach to implement one-to-one relation and mapping with DB and Hibernate from bellow Assume that we have Customer & Contact tables. 1) Can keep contact_id in Customer table as foreign key 2) Can keep customer_id in Contact table as foreign key How to implement hibernate mapping for both?

I have implemented customer and contact tables using 2nd option When i'm tryiing to do hibernatetemplate.save(customer);

i'm getting bellow Exception: Cannot add or update a child row: a foreign key constraint fails (contact_info, CONSTRAINT contact_info_ibfk_1 FOREIGN KEY (CUSTOMER_ID) REFERENCES customers (ID))

Present mapping is

@Entity
CustomerEntity {
    .....
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name="CUSTOMER_ID")
    private ContactInfoEntity contactDetails;
    .....
}
@Entity
ContactInfoEntity {

    @Column(name="CUSTOMER_ID")
    private int customerId;
}
Hrishikesh
  • 370
  • 3
  • 11

1 Answers1

0

@onetoone is always difficult and confusing to implement. You can use @ManyToOne and set the property to unique=true. It is mentioned in the Hibernate documentation that @manytoone can be used over @onetoone as it is clean that way.

Some one posted a similar question here:

Hibernate - why use many-to-one to represent a one-to-one?

Community
  • 1
  • 1
Zeus
  • 6,386
  • 6
  • 54
  • 89