user1474111
user1474111

Reputation: 1526

JoinColumn annotation creates column on same table

I am new in Hibernate and trying to learn it. I am confused about the usage of @JoinColumn. I know that it creates a column to associate two entities. What I have tried is :

  1. Having two class Person and House
  2. Person class has an set of Houses with OneToMany relation

In Person Class:

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "person_id")  // this creates a FK on house table  with this name
    private Set<House> houses = new HashSet<House>();

This creates a column with name person_id on House table.

In House Class:

    @ManyToOne
    @JoinColumn(name = "house_id")
    private Person person;

This creates house_id column again on House table. But I was expecting to see this column on Person table. Why it works like this?

I was thinking @JoinColumn annotation creates a join column on the table which is the entity which we applied this annotation to. So in this case for the Person class, it created person_id on house table and for the second one I was expecting to see house_id on person class. But it also creates it on house table. So I am confused.

So how it works actually ?

Upvotes: 1

Views: 1313

Answers (2)

imperezivan
imperezivan

Reputation: 781

try replacing @JoinColumn(name = "house_id") with @JoinColumn(name = "person_id") supposing house has a column named person_id

then remove @JoinColumn(name = "person_id") and in OneToMany annotation add the attribute mappedBy

@OneToMany(cascade = CascadeType.ALL, mappedBy = "person")

in this way hibernate will search all house where person attribute matches with current person_id

Upvotes: 0

crizzis
crizzis

Reputation: 10726

@JoinColumn creates a column where it makes sense.

For @OneToMany with @JoinColumn, the join column needs to go to the target entity table, i.e. House. If the column was created in the source entity table, i.e. Person, one person could only have a single house assigned, so it would not be a one-to-many association.

Conversely, for @ManyToOne with @JoinColumn, the join column needs to go to the source entity (i.e. House). If the column went to the Person table instead, and you assigned a given person to one house, the PERSON.HOUSE_ID column would get set to the id of that house. Then, there would be no way of assigning another house to that same person (as the PERSON.HOUSE_ID column would already be 'used'). This is essentially the same problem as before, but seen from the 'house' side of the association.

Upvotes: 1

Related Questions