As there are one to many and many to one relationships between table entities in DB , there are also similar kinds of relationships in java.

In java a one to many relationship can possibly exist on a certain column to make connecting two tables possible, but in contrary of normal database tables, All relationships in Java and JPA are unidirectional, i.e. if a source table references a target table there is no guarantee that the target table also has a relationship with the source table. That’s why there is another annotation present as of JPA 2, namely JoinColumn annotation and with the help of one of OneToMany properties, namely mappedBy property, can secure two way (bidirectional ) relationship between tables even if (and this is very important) child table doesn’t have any foreign key relating to it’s parent table, let’s look all these with a real life example between two tables of a spring based bank application below.

In the hibernate domain, two tables could enjoy a bi-directional relationship if one of them plays the role of the owner and the other ofcourse plays the role of the ownee (just invented this word). In the below example we treat two tables: account and account-type, let’s see their sqls from a closer angle:

We can see clearly that the table account (with one to many relation) has a attribute mappedBy which points to its counterpart relation table’s (account) accountType class member, and the join column annotation has account_type_id_fk as a permanent link to accountType table’s primery key (account_type_id) which will secure total bi-derectional relationship between the two tables, by this mechanism we can secure the following advantage:

We can access to account table from accountType table by hibernate’s lazy initialization:

If we have an AccountType at then,

List accounts = at.getAccounts();

And also we can access to accountType table from table account:

If we have an Account a then,

AccountType at = a.getAccountType();

Now untill here everything is cool right? wrong, there is a quite disadvantage comes along the way:

If you have the ownee to be the one who has the foreign key to the owner:

Hibernate will complain about car_owner_id_fk and car_owner_id columns, saying that they are missing from car table???

Worst: it will add them to your table if you have the property: hibernate.hbm2ddl.auto set as update.

Here you don’t have any other choice but to add a foreign key of car_owner to car table, because as explained above in hibernate the owner only has the ManyToOne, JoinColumn and the foreign key, so you need to change all your design structure or invent your own OR mapping api, is it worth it ???