• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is @JoinColumn required in one to many bidirectional relationship?

 
Himai Minh
Ranch Hand
Posts: 1361
7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In chapter 5 of JPA Pro2 , there is an example called oneToManyList,
it tries to demonstrate the one to many and many to one relationship between employees and a department.

In the Department.java :

In Employee.java



There are two tables in the DB:
Employee : ID, NAME , SALARY, DEPARTMENT_ID where ID is the primary key, Department_ID is the foreign key.
Department: ID , Name, where ID is the primary key.


I think in Employee.java, the @JoinColumn is missing even though it still works.
So, I added this to Employee.java:

 
Frits Walraven
Creator of Enthuware JWS+ V6
Saloon Keeper
Pie
Posts: 2536
113
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, @JoinColumn is only needed when the default mapping does not apply. In your case the foreign key column matches the default mapping and that is why you can leave it out.

2.10.2 Bidirectional ManyToOne / OneToMany Relationships
Assuming that:

    Entity A references a single instance of Entity B.
    Entity B references a collection of Entity A.

Entity A must be the owner of the relationship.

The following mapping defaults apply:
Entity A is mapped to a table named A.
Entity B is mapped to a table named B.
Table A contains a foreign key to table B. The foreign key column name is formed as the concatenation of the following: the name of the relationship property or field of entity A;  "_"; the name of the primary key column in table B. The foreign key column has the same type as the primary key of table B.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic