如果我使用 Hibernate Criteria API,例如:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
Root<OneEntity> entityOneRoot = criteriaQuery.from(OneEntity.class);
Root<TwoEntity> entityTwoRoot = criteriaQuery.from(TwoEntity.class);
criteriaQuery.multiselect(OneEntity, TwoEntity);
我是否需要使用 EQUAL 限制(如 SQL 中的 ON 限制)来使两个表(实体)之间的 ID 相等?因为两个表的笛卡尔积?
criteriaQuery.where(criteriaBuilder.equal(OneEntity.get("fk_id"), TwoEntity.get("id")));
我的意思是...在使用 join 的 SQL 中,我们需要使用 on-clausule,例如:
select * from table_1 t1, table_2 t2 where t1.t2_id=t2.t1_id;
但我在 API Criteria 中找不到有关它的信息。
最佳答案
来自 JPA 2.1 规范,章节 4.4.5 连接:
An inner join may be implicitly specified by the use of a cartesian product in the
FROM
clause and a join condition in theWHERE
clause. In the absence of a join condition, this reduces to the cartesian product.The main use case for this generalized style of join is when a join condition does not involve a foreign key relationship that is mapped to an entity relationship.
Example:
SELECT c FROM Customer c, Employee e WHERE c.hatsize = e.shoesize
In general, use of this style of inner join (also referred to as theta-join) is less typical than explicitly defined joins over relationships.
由于 JPQL 的工作方式与 Criteria API 相同,因此您的查询中需要同样的限制。
关于java - Hibernate 标准 aPI 多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30033415/