Hibernate : Opinions in Composite PK vs Surrogate PK

Posted by Albert Kam on Stack Overflow See other posts from Stack Overflow or by Albert Kam
Published on 2011-01-02T08:42:16Z Indexed on 2011/01/02 8:53 UTC
Read the original article Hit count: 355

As i understand it, whenever i use @Id and @GeneratedValue on a Long field inside JPA/Hibernate entity, i'm actually using a surrogate key, and i think this is a very nice way to define a primary key considering my not-so-good experiences in using composite primary keys, where :

  1. there are more than 1 business-value-columns combination that become a unique PK
  2. the composite pk values get duplicated across the table details
  3. cannot change the business value inside that composite PK

I know hibernate can support both types of PK, but im left wondering by my previous chats with experienced colleagues where they said that composite PK is easier to deal with when doing complex SQL queries and stored procedure processes.

They went on saying that when using surrogate keys will complicate things when doing joining and there are several condition when it's impossible to do some stuffs when using surrogate keys. Although im sorry i cant explain the detail here since i was not clear enough when they explain it. Maybe i'll put more details next time.

Im currently trying to do a project, and want to try out surrogate keys, since it's not getting duplicated across tables, and we can change the business-column values. And when the need for some business value combination uniqueness, i can use something like :

@Table(name="MY_TABLE", uniqueConstraints={
    @UniqueConstraint(columnNames={"FIRST_NAME", "LAST_NAME"}) // name + lastName combination must be unique

But im still in doubt because of the previous discussion about the composite key.

Could you share your experiences in this matter ? Thank you !

© Stack Overflow or respective owner

Related posts about database

Related posts about hibernate