I consider that @EmbeddedId
is probably more verbose because with @IdClass
you cannot access the entire primary key object using any field access operator. Using the @EmbeddedId
you can do like this:
@Embeddable class EmployeeId { name, dataOfBirth }
@Entity class Employee {
@EmbeddedId EmployeeId employeeId;
...
}
This gives a clear notion of the fields that make the composite key because they are all aggregated in a class that is accessed trough a field access operator.
Another difference with @IdClass
and @EmbeddedId
is when it comes to write HQL :
With @IdClass
you write:
select e.name from Employee e
and with @EmbeddedId
you have to write:
select e.employeeId.name from Employee e
You have to write more text for the same query. Some may argue that this differs from a more natural language like the one promoted by IdClass
. But most of the times understanding right from the query that a given field is part of the composite key is of invaluable help.
@IdClass
even though I prefer@EmbeddedId
in most situations (Got to know this from a session by Antonio Goncalves .What he suggested is we could use the@IdClass
in case the composite key class is not accessible or comes in from another module or legacy code where we can't add a annotation .In those scenarios@IdClass
will give us a way our . – Solenoid