Kdeveloper
Kdeveloper

Reputation: 13819

JPA: default column name mapping for @ManyToOne relations

When we have a class:

@Entity
Order implements Serializable {
    @Id
    private Integer id;
    ...
}

and:

@Entity
OrderLine implements Serializable {
    @Id
    private Integer id;

    @ManyToOne
    Order order;
    ...
}

What row name will the property order map to?

order_id, ORDER_ID or Order_id?

(ommiting the @JoinColumn(name='order_id') is deliberate)

Upvotes: 38

Views: 55279

Answers (2)

Pascal Thivent
Pascal Thivent

Reputation: 570385

Here is what the JPA 1.0 specification writes about the JoinColumn annotation:

9.1.6 JoinColumn Annotation

...

The name annotation element defines the name of the foreign key column. The remaining annotation elements (other than referencedColumnName) refer to this column and have the same semantics as for the Column annotation.

If there is a single join column, and if the name annotation member is missing, the join column name is formed as the concatenation of the following: the name of the referencing relationship property or field of the referencing entity; "_"; the name of the referenced primary key column. If there is no such referencing relationship property or field in the entity (i.e., a join table is used), the join column name is formed as the concatenation of the following: the name of the entity; "_"; the name of the referenced primary key column.

...

So in your example, the default name of the foreign key column would be order_id.

References

  • JPA 1.0 specification
    • Section 9.1.6 "JoinColumn Annotation"

Upvotes: 40

Oscar Chan
Oscar Chan

Reputation: 1612

I might not understand your question. However, don't you need something like below?

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="order_id", nullable=false)
Order order;

here are some examples

Upvotes: 50

Related Questions