Difference using @Id and @EmbeddedId for a compound key

Viewed 68880

I've created an entity that uses @Id to point to an @Embeddable compound key. Everything I believe works fine as is. However, after switching @Id to @EmbeddedId everything continues to work fine as far as I can tell.

Before:

@Entity
public final class MyEntity {
    private CompoundKey id;

    @Id
    public CompoundKey getId() {
        return id;
    }

    public void setId(CompoundKey id) {
        this.id = id;
    }

After:

@Entity
public final class MyEntity {
    private CompoundKey id;

    @EmbeddedId
    public CompoundKey getId() {
        return id;
    }

    public void setId(CompoundKey id) {
        this.id = id;
    }

Is there a difference between using the @Id and @EmbeddedId annotations when referencing a compound key?

2 Answers

I referred hibernate docs Hiberate 3.5 annotations reference whereby there is the difference that with @EmbeddedId you can skip annotating the entity class @Embeddable but with @Id it's required.

I tried using @Id without @Embeddable it gives exception:

org.hibernate.mapping.SimpleValue cannot be cast to org.hibernate.mapping.Component

Just this and no extra info like the field or class name.

Well this behavior is as of Hibernate 4; I don't know about other JPA providers. I will test a few and update post accordingly if there are any more findings.

Related