【问题标题】:JPA - Why cast Fetch to JoinJPA - 为什么选择 Fetch 来加入
【发布时间】:2017-10-04 07:21:41
【问题描述】:

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

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);

【问题讨论】:

  • 既然javax.persistence.criteria.Fetch 不一定是javax.persistence.criteria.Join,那么(对我来说)它没有任何意义。

标签: jpa jpa-criteria


【解决方案1】:

当我想同时获得两者的好处时,我不得不将 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

【讨论】:

  • 我认为它不再起作用了。我在将 Fetch 转换为 Join 时遇到了很多麻烦。你有什么建议吗?
【解决方案2】:

确定的答案在这里:How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

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

@*ToOne 连接没有问题,因此一些 JPA 实现允许将 Fetch 转换为 Join 假设您了解自己在做什么))

其他阅读:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    相关资源
    最近更新 更多