redochka
redochka

Reputation: 12829

Why is hibernate creating a join table as well as a join column?

Here is the two classes that I'm use to express a bidirectional OneToMany relationship.

Class Contact {
    @OneToMany
    public Set getPhoneNumbers() {
        return phoneNumbers;
    }
}
Class PhoneNumber{
    @ManyToOne
    public Contact getContact() {
        return contact;
    }
}

Hibernate is creating a join table (which I think is good for my need)

contact_phonenumber
   -Contact_id
   -phoneNumbers_id

but why is it creating this extra join column (contact_id) on the phoneNumber table

phonenumber
  -id
  -contact_id
  -...

Isn't the join table enough?

More over, when I save a phonenumber or contact, the join table is updated but not the join column. So why is this join column here?

Thanks for your help.

Upvotes: 2

Views: 1004

Answers (1)

redochka
redochka

Reputation: 12829

I found a solution:

Class Contact {
    @OneToMany(mappedBy="contact", targetEntity=PhoneNumber.class, orphanRemoval=false)
    public Set getPhoneNumbers() {
        return phoneNumbers;
    }
}
Class PhoneNumber{
    @ManyToOne
    @JoinTable(name="t_join_contact_phonenumber", joinColumns=@JoinColumn(name="PHONENUMBER_ID"), inverseJoinColumns=@JoinColumn(name="CONTACT_ID"))
    public Contact getContact() {
        return contact;
    }
}

Now, Hibernate is creating the join table only

t_join_contact_phonenumber
   -CONTACT_ID
   -PHONENUMBER_ID

Thanks.

Upvotes: 1

Related Questions