简体   繁体   English

@JoinColumn注释在Hibernate中是必需的吗?

[英]Is @JoinColumn annotation mandatory in Hibernate?

In Hibernate, to specify a column for joining association, @JoinColumn annotation in used, for example like this: 在Hibernate中,要指定一个用于连接关联的列,使用@JoinColumn注释,例如:

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

In most cases, name of the column is snaked-cased class name plus _id . 在大多数情况下,列的名称是snaked-cased类名加_id So it is reasonable to expect from Hibernate to derive it automatically (as it is done, for example, in Django's ORM). 因此,期望Hibernate自动派生它是合理的(例如,在Django的ORM中完成)。 But is such behavior implemented somehow? 但这种行为是以某种方式实施的吗?

It is not necessary, JPA follows convention over configuration principle which means there are allways some default values that you can override with annotations. 没有必要,JPA遵循约定优于配置原则,这意味着总有一些默认值可以用注释覆盖。

In case of @JoinColumn , the default column name is generated like this: <field_name>_<id_column_name> 对于@JoinColumn ,默认列名称生成如下: <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 . field_name是您的案例中的addressid_column_name是指相关实体的id,即id Thus, you get address_id by default. 因此,您默认获得address_id

It is not necessary to have @JoinColumn annotation. 没有必要使用@JoinColumn注释。 You can always override it. 你总是可以覆盖它。 If you won't provide it in your code then Hibernate will automatically generate one for you ie default name for your column. 如果您不在代码中提供它,那么Hibernate会自动为您生成一个,即列的默认名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM