我应该使用哪种注释:@IdClass或@EmbeddedId [英] Which annotation should I use: @IdClass or @EmbeddedId
问题描述
的 JPA
(Java持久性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
你必须写:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!