JPA JoinColumn vs mappedBy

In a JPA entity mapping, the @JoinColumn annotation is used to specify the foreign key column for a many-to-one or one-to-one relationship. It is used on the side of the relationship that "owns" the foreign key.

For example, consider a Person entity that has a many-to-one relationship with a Department entity:

@Entity
public class Person {
    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
    // ...
}

In this example, the @JoinColumn annotation specifies that the Person entity has a foreign key column called department_id, which refers to the primary key of the Department entity.

On the other hand, the mappedBy attribute of the @OneToOne and @ManyToOne annotations is used to specify the inverse side of a one-to-one or many-to-one relationship. It is used on the side of the relationship that does not "own" the foreign key.

For example, consider the following entity mapping:

@Entity
public class Department {
    @OneToOne(mappedBy = "department")
    private Person person;
    // ...
}

In this example, the mappedBy attribute specifies that the Department entity is the inverse side of a one-to-one relationship with the Person entity, and that the foreign key is on the Person side of the relationship (as specified by the @JoinColumn annotation in the Person entity).

The @JoinColumn annotation is used to specify the foreign key column for the relationship, while the mappedBy attribute is used to specify the inverse side of the relationship.