JPA:如何热切获取嵌入式元素集合 [英] JPA: How to fetch eagerly an embedded element collection
问题描述
考虑以下模型
@Entity
// JPA and JAXB annotations here
public class Employee implements Serializable {
// other fields, annotations, stuffs
...
@ElementCollection(fetch = FetchType.LAZY,
targetClass = Address.class)
@CollectionTable(name = "employee_address",
schema = "hris",
joinColumns = @JoinColumn(name = "employee_id",
nullable = false,
referencedColumnName = "employee_id",
foreignKey = @ForeignKey(ConstraintMode.CONSTRAINT)))
protected Set<Address> addresses;
// setters, getters
...
}
@Embeddable
// JAXB annotations here
public class Address implements Serializable {
// fields, setters, getters
}
Address
类带有@Embeddable
注释,而Employee
类具有addresses
的嵌入式元素集合.元素集合的fetch
设置为FetchType.LAZY
.现在,我想创建一个@NamedQuery
,该地址将检索所有具有预先初始化地址的雇员.知道JOIN FETCH
仅适用于带有@ManyToMany
基于JPA 2.1,我将如何创建有效的JPQL
查询,以使我能够急切地检索嵌入式元素集合?
The Address
class is annotated with @Embeddable
annotation, and the Employee
class has an embedded element collection of addresses
. The element collection's fetch
is set to FetchType.LAZY
. Now, I would like to create a @NamedQuery
that would retrieve all employees with addresses eagerly initialized. Knowing that JOIN FETCH
will only work with entity collections annotated with @OneToMany
or @ManyToMany
based on JPA 2.1, how would I create a valid JPQL
query that would allow me to eagerly retrieve embedded element collections?
推荐答案
在JPA 2.1规范(JSR 338)中,我找不到任何提示,表明访存联接仅适用于实体关系(但不适用于可嵌入对象). JSR 338第4.4.5.3节甚至规定:
In the JPA 2.1 specification (JSR 338) I cannot find any hint that fetch joins only work on entity relationships (but not embeddables). JSR 338, section 4.4.5.3 even states:
FETCH JOIN
允许获取关联或元素集合,作为执行查询的副作用.
A
FETCH JOIN
enables the fetching of an association or element collection as a side effect of the execution of a query.
作为另一个提示,以下是作为JPA提供程序使用Hibernate 4.3.11执行的最小示例(基本上类似于您的示例)会导致单个查询:
As another hint the following minimal example (essentially resembling yours) executed with Hibernate 4.3.11 as JPA provider results in a single query:
可嵌入地址:
@Embeddable public class Address { private String city; }
员工实体:
@Entity public class Employee {
@Id private Long id;
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "address",
joinColumns = @JoinColumn(name="employee_id"))
private Set<Address> addresses;
}
JPQL查询:
em.createQuery("select e from Employee e join fetch e.addresses").getResultList();
产生的SQL查询:
select
employee0_.id as id1_1_,
addresses1_.employee_id as employee1_1_0__,
addresses1_.city as city2_5_0__
from
Employee employee0_
inner join
address addresses1_ on employee0_.id=addresses1_.employee_id
因此上述JPQL查询似乎可以解决您的问题.
So the above JPQL query seems to solve your problem.
这篇关于JPA:如何热切获取嵌入式元素集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!