2

Why is it necessary sometimes to cast?

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

For Example:

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

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

What is the reason for not doing:

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

2 回答 2

2

Fetch当我想Join同时获得两者的好处时,我不得不投降。

例如,假设您想将Employee有关其部门和本国的信息作为具有两个内部联接的单个选择查询收集在一起。这可以通过添加root.fetch(...)each fordepartment和来实现homeCountry。如果您还希望根据各自所在国家/地区的人口对员工进行排序(请假设您愿意),您将需要一个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
于 2018-03-31T18:25:55.760 回答
0

明确的答案就在这里:如何正确地将带有“where”子句的 JPQL“join fetch”表示为 JPA 2 CriteriaQuery?

基本上,JPA 提供@OneToMany了需要将所有相关实体提取到Collection. 如果您允许对Fetch(as javax.persistence.criteria.Path.get(String)) 进行别名,则可以添加限制破坏 JPA Java 模型假设的where表达式。onCollection

连接没有问题,@*ToOne因此一些 JPA 实现允许强制转换FetchJoin假设您了解您在做什么))

其他阅读:

于 2020-07-20T11:12:51.477 回答