6

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?

Bacteria
  • 8,406
  • 10
  • 50
  • 67
Mikhail Batcer
  • 1,938
  • 7
  • 37
  • 57
  • JPA has a default naming convention, visible in the JPA spec. As shown by this link http://www.datanucleus.org/products/accessplatform_4_2/jpa/orm/datastore_identifiers.html#rdbms_jpa – Neil Stockton Jan 14 '16 at 11:14
  • If you don't use it, you might end up with an uneccessary join-table. – Tobb Jan 14 '16 at 11:21

2 Answers2

16

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.

Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • What if I need column name in snake_case (like `postal_code`), while field name is in lowerCamelCase (`postalCode`)? – Mikhail Batcer Jan 14 '16 at 11:36
  • 1
    If you need to override the default naming convention then that's exactly what @JoinColumn is for. – Tobb Jan 14 '16 at 11:44
  • @Tobb It's a local override, which has to be repeated everywhere. It overrides just one column name. Is it possible to override naming convention itself, in one place (e.g. config file) for all project? – Mikhail Batcer Jan 14 '16 at 12:42
  • Not to my knowledge. At least I don't think it's part of the JPA spec, maybe some provider will let you do so. – Tobb Jan 14 '16 at 13:11
  • 2
    @MikhailBatcer Since you seem to be using Hibernate, you can implement you own `org.hibernate.cfg.NamingStrategy` and register it by using parameter `hibernate.ejb.naming_strategy`. Check out [this link](http://www.petrikainulainen.net/programming/tips-and-tricks/implementing-a-custom-namingstrategy-with-hibernate/) for more information. – Predrag Maric Jan 14 '16 at 13:22
3

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.