Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 836
Mikhail Batcer Avatar asked Dec 06 '22 19:12

Mikhail Batcer


2 Answers

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.

like image 66
Predrag Maric Avatar answered Dec 18 '22 05:12

Predrag Maric


It is not necessary to have @JoinColumn annotation. You can always override it. If you won't provide it in your code then Hibernate will automatically generate one for you i.e. default name for your column.

like image 29
Meeti Srivastava Avatar answered Dec 18 '22 05:12

Meeti Srivastava