我有一个Domain
实体与@ManyToOne
实体的Country
单向关系,我想热切地加载JOIN而不是单独的选择。我考虑过使用@Fetch
。
@Entity
@Table
public class Domain {
@Id
@GenericGenerator(name = "generator", strategy = "increment")
@GeneratedValue(generator = "generator")
@Column(name = "domain_id")
private Long domainId;
@Fetch(FetchMode.JOIN)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Country country;
...
}
我正在使用HQL
来查询这些实体。
但是Hibernate不应用提取策略。我试过@OneToOne
(我的设计中没有改变任何东西),但这也行不通。这是一个示例SQL输出
Hibernate: select domain0_.domain_id as domain1_2_, domain0_.country as country2_, domain0_.name as name2_, domain0_.type as type2_ from domain domain0_ order by domain0_.name limit ?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?
Hibernate: select country0_.country_id as country1_1_0_, country0_.code as code1_0_, country0_.currency as currency1_0_, country0_.name as name1_0_ from country country0_ where country0_.country_id=?
我假设某些东西阻止它被应用。那是什么?
答案 0 :(得分:1)
我正在查询我的Domain
实体,例如
FROM Domain domain WHERE domain.type = :type
这导致Hibernate为返回的每个Country
单独查询Domain
个实体。
根据汤姆安德森的评论和答案here,我将我的HQL更改为
FROM Domain domain JOIN FETCH domain.country WHERE domain.type = :type
这会导致Hibernate只使用一个带有连接的大查询来一起检索Domain
和Country
,而不是对所有Domain
个实体和SELECT
进行一次查询}为每个人检索Country
。
使用Criteria
,似乎没有必要。只有在使用HQL时才需要指定JOIN FETCH
。