问题描述
JPA
(Java Persistence API)规范有两种不同的方式来指定实体复合键:@IdClass
和 @EmbeddedId
.
The JPA
(Java Persistence API) specification has 2 different ways to specify entity composite keys: @IdClass
and @EmbeddedId
.
我在我的映射实体上同时使用了这两个注释,但对于那些不太熟悉 JPA
的人来说,结果是一团糟.
I'm using both annotations on my mapped entities, but it turns out to be a big mess to people who aren't very familiar with JPA
.
我只想采用一种方式来指定复合键.哪一个真的是最好的?为什么?
I want to adopt only one way to specify composite keys. Which one is really the best? Why?
推荐答案
我认为 @EmbeddedId
可能更冗长,因为使用 @IdClass
你不能访问整个主要使用任何字段访问运算符的键对象.使用 @EmbeddedId
你可以这样做:
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.
@IdClass
和 @EmbeddedId
的另一个区别在于编写 HQL 时:
Another difference with @IdClass
and @EmbeddedId
is when it comes to write HQL :
使用 @IdClass
你写:
select e.name from Employee e
并且使用 @EmbeddedId
你必须写:
and with @EmbeddedId
you have to write:
select e.employeeId.name from Employee e
您必须为同一查询编写更多文本.有些人可能会争辩说,这与 IdClass
所提倡的更自然的语言不同.但大多数情况下,直接从查询中理解给定字段是组合键的一部分是非常有用的.
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 或 @EmbeddedId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!