本文介绍了使用 JPA Criteria API,您能否执行仅导致一个连接的获取连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 使用 JPA 2.0.似乎默认情况下(没有显式获取),@OneToOne(fetch = FetchType.EAGER) 字段在 1 + N 个查询中获取,其中 N 是包含定义关系的实体的结果数到一个不同的相关实体.使用 Criteria API,我可能会尝试避免这种情况,如下所示:Using JPA 2.0. It seems that by default (no explicit fetch), @OneToOne(fetch = FetchType.EAGER) fields are fetched in 1 + N queries, where N is the number of results containing an Entity that defines the relationship to a distinct related entity. Using the Criteria API, I might try to avoid that as follows:CriteriaBuilder builder = entityManager.getCriteriaBuilder();CriteriaQuery<MyEntity> query = builder.createQuery(MyEntity.class);Root<MyEntity> root = query.from(MyEntity.class);Join<MyEntity, RelatedEntity> join = root.join("relatedEntity");root.fetch("relatedEntity");query.select(root).where(builder.equals(join.get("id"), 3));理想情况下,上述内容应等效于以下内容:The above should ideally be equivalent to the following:SELECT m FROM MyEntity m JOIN FETCH myEntity.relatedEntity r WHERE r.id = 3然而,条件查询导致根表不必要地连接到相关实体表两次;一次用于获取,一次用于 where 谓词.生成的 SQL 看起来像这样:However, the criteria query results in the root table needlessly being joined to the related entity table twice; once for the fetch, and once for the where predicate. The resulting SQL looks something like this:SELECT myentity.id, myentity.attribute, relatedentity2.id, relatedentity2.attributeFROM my_entity myentityINNER JOIN related_entity relatedentity1 ON myentity.related_id = relatedentity1.idINNER JOIN related_entity relatedentity2 ON myentity.related_id = relatedentity2.idWHERE relatedentity1.id = 3唉,如果我只做提取,那么我就没有在 where 子句中使用的表达式.Alas, if I only do the fetch, then I don't have an expression to use in the where clause.我是否遗漏了什么,或者这是 Criteria API 的限制?如果是后者,这是否在 JPA 2.1 中得到纠正,或者是否有任何特定于供应商的增强功能?Am I missing something, or is this a limitation of the Criteria API? If it's the latter, is this being remedied in JPA 2.1 or are there any vendor-specific enhancements?否则,最好放弃编译时类型检查(我意识到我的示例没有使用元模型)并使用动态 JPQL TypedQueries.Otherwise, it seems better to just give up compile-time type checking (I realize my example doesn't use the metamodel) and use dynamic JPQL TypedQueries.推荐答案你可以使用 root.fetch(...) 代替 root.join(...)code> 返回 Fetch 对象.Instead of root.join(...) you can use root.fetch(...) which returns Fetch<> object.Fetch 是 Join 的后代,但它可以以类似的方式使用.Fetch<> is descendant of Join<> but it can be used in similar manner.您只需要将 Fetch 转换为 Join 它应该适用于 EclipseLink 和 HibernateYou just need to cast Fetch<> to Join<> it should work for EclipseLink and Hibernate...Join<MyEntity, RelatedEntity> join = (Join<MyEntity, RelatedEntity>)root.fetch("relatedEntity");... 这篇关于使用 JPA Criteria API,您能否执行仅导致一个连接的获取连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-31 00:06