JPA-为什么要加入
为什么有时有必要投下JPA-为什么要加入,jpa,jpa-criteria,Jpa,Jpa Criteria,为什么有时有必要投下 Join<X, Y> a = (Join) Fetch<X, Y> ... Join a=(Join)Fetch。。。 例如: Root<Person> personRoot = criteriaQuery.from(Person.class); @SuppressWarnings("unchecked") Join<Person, Loan> loanJoin = (Join) personRoot.fetch("lo
Join<X, Y> a = (Join) Fetch<X, Y> ...
Join a=(Join)Fetch。。。
例如:
Root<Person> personRoot = criteriaQuery.from(Person.class);
@SuppressWarnings("unchecked")
Join<Person, Loan> loanJoin = (Join) personRoot.fetch("loan", JoinType.INNER);
loanJoin.fetch("borrower", JoinType.LEFT);
Root personRoot=criteriaQuery.from(Person.class);
@抑制警告(“未选中”)
Join-loanJoin=(Join)personRoot.fetch(“loan”,JoinType.INNER);
loanJoin.fetch(“借用者”,JoinType.LEFT);
不这样做的原因是什么:
Fetch<Person, Loan> fetchJoin = personRoot.fetch("loan", JoinType.INNER);
fetchJoin.fetch("borrower", JoinType.LEFT);
Fetch fetchJoin=personRoot.Fetch(“loan”,JoinType.INNER);
fetchJoin.fetch(“借款人”,JoinType.LEFT);
当我想同时获得两者的好处时,我不得不将
提取转换为加入
Fetch
允许在批注不起作用时立即加载,请参见
Join
允许对已联接关系中的属性添加限制/顺序
e、 例如,假设您希望将所有员工
及其部门和母国的信息作为一个带有两个内部联接的select查询获取。这可以通过为部门
和母国
分别添加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();
确切的答案是:
基本上,JPA提供了@OneToMany
,需要将所有相关实体提取到集合
。如果您允许对Fetch
(作为javax.persistence.criteria.Path.get(String)
)使用别名,则可以在中添加,或者在表达式上添加,以限制收集
打破JPA Java模型假设
@*ToOne
连接没有问题,因此一些JPA实现允许将Fetch
转换为Join
,前提是您了解自己在做什么)
其他案文:
既然javax.persistence.criteria.Fetch
不一定是javax.persistence.criteria.Join
,那么(对我来说)它就毫无意义了。
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