Search code examples
javahibernatejpajoincolumn

Is @JoinColumn annotation mandatory in Hibernate?


In Hibernate, to specify a column for joining association, @JoinColumn annotation in used, for example like this:

@ManyToOne
@JoinColumn(name="address_id")
public Address getAddress() { 
    return address; 
}

In most cases, name of the column is snaked-cased class name plus _id. So it is reasonable to expect from Hibernate to derive it automatically (as it is done, for example, in Django's ORM). But is such behavior implemented somehow?


Solution

  • It is not necessary, JPA follows convention over configuration principle which means there are allways some default values that you can override with annotations.

    In case of @JoinColumn, the default column name is generated like this: <field_name>_<id_column_name>

    field_name is address in your case, and id_column_name is referring to the related entity's id, which is id. Thus, you get address_id by default.