开发者

how , where and when to use natural-id in hbm file in hibernate?

I searched a lot in google but i didn't find any satisfied answer. So any one any please tell me a senario, where to use natural-id in hbm file in hibernat开发者_高级运维e. Any help would be greatly appreciated.

Thanks in advance.....


You are strongly encouraged to use a surrogate primary key on your tables, i.e. a column called id which is not derived from the business data. However there is most likely a combination of fields which form a sensible business key for a table. These fields should be non-null and immutable. This is what would be marked as the natural key and would also be used in the equals and hashCode implementations for that class.

If Hibernate were to generate your database schema from your mapped domain classes this natural key would be used to generate a unique index for the table.


Your question is a little vague, but a reason to use the Natural-Id in the hbm file would be to automatically enforce things that should be unique. That property is supposed to be assigned to the fields that make your data unique. When you place the attribute on those fields hibernate will generate unique indexes for you.

If your question is Why should one ever use natural keys? There are too many to list here but an easy example...

If you decide to expose your data via webservices, feeds, etc., it's not a good idea to give end users the keys to your database. This is bad for many reasons, one of which is what happens if they store it, and you re-key? You are stuck! Its best to talk in terms they understand, which would be things already present in the data (naturally ;) )

If you are interested in reading about this on your own AgileData.org has a great blurb about Natural vs Surrogate

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜