gpt4 book ai didi

JPA - 为什么投 Fetch 加入

转载 作者:行者123 更新时间:2023-12-05 05:20:59 25 4
gpt4 key购买 nike

为什么有时需要强制转换?

Join<X, Y> a = (Join) Fetch<X, Y> ...

例如:

Root<Person> personRoot = criteriaQuery.from(Person.class);

@SuppressWarnings("unchecked")
Join<Person, Loan> loanJoin = (Join) personRoot.fetch("loan", JoinType.INNER);
loanJoin.fetch("borrower", JoinType.LEFT);

没有做的原因是什么:

Fetch<Person, Loan> fetchJoin = personRoot.fetch("loan", JoinType.INNER);
fetchJoin.fetch("borrower", JoinType.LEFT);

最佳答案

当我想获得两者的好处时,我不得不将 Fetch 转换为 Join

例如,假设您希望将所有 Employee 及其部门和所在国家/地区的信息作为具有两个内部联接的单个选择查询一起获取。这可以通过为 departmenthomeCountry 添加一个 root.fetch(...) 来实现。如果您还希望根据各自所在国家/地区的人口对员工进行排序(请假设您愿意),您将需要一个Join

Root<Employee> root = query.from(Employee.class);
root.fetch("department"); // <- for an eager join
Join<Employee,Country> joinCountry = (Join) root.fetch("homeCountry"); // <- for an eager join & orderBy
query.select(root).orderBy(builder.asc(joinCountry.get("population")));
Query<Employee> q = sessionFactory.getCurrentSession().createQuery(query);
List<Employee> employees = q.getResultList();

上面的代码向数据库触发了一个select *

select
employee0_.emp_id as emp_id1_0_0_,
department1_.department_id as depart1_2_1_,
country2_.country_id as countr1_3_2_,
employee0_.salary as salary2_0_0_,
department1_.name as name3_0_0,
country2_.continent as continent4_0_0
from
employee employee0_
inner join
department department1_
on employee0_.department_id=department1_.department_id
inner join
country country2_
on employee0_.country_id=country2_.country_id
order by
country2_.population asc

关于JPA - 为什么投 Fetch 加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43811234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com