Should I use composite primary keys or not?

后端 未结 10 595
别那么骄傲
别那么骄傲 2020-12-03 07:28

There seems to only be 2nd class support for composite database keys in Java\'s JPA (via EmbeddedId or IdClass annotations). And when I read up on composite keys, regardless

10条回答
  •  醉梦人生
    2020-12-03 08:11

    In my personal opinion you should avoid composite primary keys due to several reasons:

    1. Future changes: when you design a database you sometimes miss what in the future will become important. A significant example for this is thinking a combination of two or more fields is unique (and thus can become a primary key), whereas in the future you want to allow NULLs or other non-unique values in them. Having a single primary key is a good solid solution against such changes.

    2. Uniformity: If every table has a unique numerical ID, and you also maintain some standard as to its name (e.g. "ID" or "tablename_id"), the code and SQL referring to it is clearer (in my opinion).

    There are other reasons, but these are just a few.

    The main question I would ask is why not use a separate primary key if you have a unique set of fields? What's the cost? An additional integer index? That's not too bad.

    Hope that helps.

提交回复
热议问题