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

ぃ、小莉子 提交于 2019-11-28 10:42:36

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.

Kawu

As Pascal wrote here's part of the answer:

Which annotation should I use: @IdClass or @EmbeddedId

In the end, I believe using @IdClass is much easier in practice, because you have to add the embeddedId property name to dereference PK properties, while these aren't written for all non-PK properties.

You always have to remember exactly which properties are part of a PK and those which are not. That complicates writing JPQL queries unneccessarily.

Also, AFAIK the JPA 2.0 spec allows you to put @Id onto @XToX/@JoinColumn/s properties and it introduces the @MapsId annotation, so that mapping identifying relationships (a.k.a. derived identifiers in JPA) are more natural to implement.

I. Remember using idclass to do it. But I'd recommend doing everything you can to avoid multi field keys. They just create extra work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!