JPA/Hibernate: What's better for composite primary keys, @IdClass or @EmbeddedId implementations and why?

Kawu picture Kawu · Oct 26, 2010 · Viewed 17.9k times · Source

what's better for JPA/Hibernate composite primary keys, @IdClass or @EmbeddedId implementations and why?

This is an intentionally naive question. I decided to use @EmbeddedId (for whatever reason) and I feel like I made the wrong choice. Dereferencing the embeddedId that contains the column properties is redundant and quite error-prone when coding.

Are there any more reasons for and/or against the other? Is the a recommendation by the JPA (spec)?

Answer

Victor Stafusa picture Victor Stafusa · Dec 27, 2010

First, if possible, avoid composite ids at all costs. But if you really need, I would recommend @EmbeddedId.

@IdClass is basically a leftover from EJB 2.1 times to make it easier from migrating from BMP. In some other rare corner cases it may be better than @EmbeddedId too. However, generally @EmbeddedId is better and more OO since it encapsulates the concept os the key much better in the object.

You may want to use @AttributeOverride(s) if you need in the key field.

I don't see why do you think that dereferencing the embedded id is redundant and error-prone.