Disabling foreign key generation in hbm2ddl
When generating the database schema using the hbm2ddl tools, foreign keys are being created for every relation. You can enhance the schema by using the foreign-key attribute to specify your own name for a particular foreign key.
But, what happens when you don’t want a foreign key generated?
There is an undocumented behavior of the foreign-key attribute, and that is to specify foreign-key=”none”. hbm2ddl will not create an FK for a relation which has such an attribute. The hibernate documentation and the two bibles Hibernate in Action and Java Persistence with Hibernate state absolutely nothing about this feature. I found it after hardcore googling in the following hibernate changelog:
Changes in version 2.1.9 (xx.x.xxxx) ------------------------------------ * foreign-key="none" can be used to disable generation of a foreign key.
Later on, I found another blog mentioning this behavior: http://blog.xebia.com/2007/02/05/let-hibernate-connect-your-world/
The most logical question now is “why don’t you want an FK?”. That depends on the system you are building. Sometimes you might have a table in your application which will be CRUDed from another system, which you do not control. You may want to be able to keep references (ids) to entities which may be deleted. foreign-key=”none” together with not-found=”ignore” can solve these kind of problems.
September 5th, 2008 at 7:55
Awesome. I need to eliminate foreign keys for my history tables which are mostly duplicates of my regular JPA entities.
January 18th, 2009 at 0:49
Cheers for that – save me heaps of time
February 8th, 2009 at 16:43
>The most logical question now is “why don’t you want an FK?”.
Depends on which database you are using and what you are doing.
If you never actually join across the tables having a foreign key, the key only gives you referential integrity assurance. Referential integrity can be assured in other ways.
Some databases do not cope with foreign keys and composite primary keys nicely. I have seen examples of tables where the index and key spaces were an order of magnitude larger than the data set. This is a major issue if you have nontrivial amounts of data.