I have to design a table for storing some remote data. The data I am getting, via web service, has a candidate key, combination of two columns, but I have seen few posts where they discourage using composite-key in hibernate instead recommending to use surrogate-key. If I design a table using composite-key then I can update the data directly but if I use surrogate-key then I have to fetch the primary-key first before updating. My question is which one should I use, composite-key or surrogate-key?
1 Answers
Say no to Composite Key becasue...
- They are inefficient (depends on the database)
- cumbersome to use
- More number of parameters instead of just one
- prone to bugs
- May lead to duplciation of data if we have more than one column as composite key
Hence surrogate key is suggested. Though it has its own drawbacks
- Performance problems
- Error prone
- Duplication
As stated in Java Persistence with Hibernate reference:
More experienced Hibernate users use saveOrUpdate() exclusively; it’s much easier to let Hibernate decide what is new and what is old, especially in a more complex network of objects with mixed state. The only (not really serious) disadvantage of exclusive saveOrUpdate() is that it sometimes can’t guess whether an instance is old or new without firing a SELECT at the database—for example, when a class is mapped with a natural composite key and no version or timestamp property.
Some manifestations of the limitation can be found here.
So use natural keys when it is relevant to do so and use surrogate keys when it is better to use them.
-
I have to update more than a million record, if I use surrogate-key then I have to do a select and update for all the record. Is there any way to improve the performance? – msmani Jul 10 '15 at 06:23
-
updating a million records sounds like you might want to do this without hibernate at all. – Jens Schauder Jul 10 '15 at 06:59