Let me start my first accepting a misconception which I had till very recently. I sort of always assumed that foreign keys are always indexed. A little more digging revealed that Oracle, DB2 and even SQL server does not create an index for a foreign key automatically. So it has to be explicitly done.
We all know indexes has cost associated to it. Apart from using the storage space, it has to be maintained by the database on inserts and updates but still it is very good idea to create an index for a foreign key and especially when
- We have a use case where deletion of the parent row cascades into deletion on the child table. Otherwise it will lead to a full table scan of the child table for each parent row deletion.
- We frequently join parent and child tables. Otherwise it will have a performance impact.
So basically a little bit of a trade off as what we really want to do but in general it is always a good idea to have an index on a foreign key.
But does all this have any impact on how we do our Hibernate mappings, yes for sure. So for example if we decide to not index a foreign key, then
- Be careful while using : on-delete=”cascade” even though the database has a support for it
- Always specify lazy=”true” to prevent a join and eager fetch of the child rows.