It's not a secret anymore!
The moose likes Object Relational Mapping and the fly likes JPA - foreign key filed question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "JPA - foreign key filed question" Watch "JPA - foreign key filed question" New topic

JPA - foreign key filed question

Witold Marshal
Ranch Hand

Joined: Feb 05, 2012
Posts: 48
I have recently started my adventure with JPA (2.0) and i have a question about foreign keycolumn which is defined in anotation for relation @JoinColumn(name="foreign_key").
For example let's take OneToOne biderectional relation for two entities Order and Invoice where Invoice is an "owning" side. So the foregin key column is in Invoice table in data base with name Order_Id. The Order_Id is a primary key (int) in Order entity.
My relation from Invoice side would look like thid
publi class Invoice {


@JoinColumn(name ="Order_Id" )
public Order getOrder() {
return order;

private Order order;

// private int Order_Id; // should it be defined in this entity?

The question is whether this entity (Invoice) should possess definded field (or property) Order_Id which would be mapped on Invoice table foreign key column?
I ask about it because I have seen both cases in examples (with such field and without it) and i suppose that one of them must be wrong.

Ram Narayan.M
Ranch Hand

Joined: Jul 11, 2010
Posts: 247

private Order order;

Defining like this is correct one... Since all are done in Object Oriented manner... Invoice "has"(possess) Order object... JPA Entity Manager will deal the foreign key mapping between Invoice and Order with the help of annotation "JoinColumn"... Thats the purpose JoinColumn annotation serves here...

Defining directly the "Order_id" int type means manually we have to give the Order id by not utilizing the Entity Manager Auto-Mapping feature...

When persisting the new Invoice object, the new Invoice object should have "Order" object set in the new Invoice object..

While making an insertion of new Invoice object as relational record in relational database, implicitly Entity Manager search for "Order_Id" DB field name (Order Table Primary Key field) mapped instance variable in Order object and maps to foreign key column "Order_Id" of Invoice table...


insert into Invoice(col1,col2,Order_Id) values(val_col1,val_col2,<Order_Id_value extracted from Order object which was possessed by Invoice Object>)

SCJP 6 [SCJP - Old is Gold]
Witold Marshal
Ranch Hand

Joined: Feb 05, 2012
Posts: 48
Thanks : )
I agree. Here's the link:
subject: JPA - foreign key filed question
jQuery in Action, 3rd edition