如何将带有子查询的 JPQL 转换为等效的 Criteria API? [英] How to convert a JPQL with subquery to Criteria API equivalent?

查看:22
本文介绍了如何将带有子查询的 JPQL 转换为等效的 Criteria API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个由 5 个实体组成的简单对象模型:

Have a simple object model made up of 5 entities:

  1. 公司
  2. 组织
  3. 地址
  4. 俱乐部

一家公司与一个组织相关联.(组和俱乐部也与单个组织相关联 - 这些是单向的,这意味着组织不包含对其所有者的引用).一个组织可能有 0 个或多个地址.

A Company is associated with a single Organization. (Group and Club are also associated with a single Organization - these are unidirectional, meaning the Organization does not contain a reference to its owner). An Organization may have 0 or more Address(es).

子查询可用于访问基于特定邮政编码的公司对象,邮政编码是地址的一个属性.这是一个可以访问具有特定邮政编码的公司的 JPQL 查询.

A subquery can be used to access Company objects based on a specific zipcode, which is an attribute of an Address. Here is a JPQL query that can access those companies with a specific zipcode.

@Query("select p from Company p, Organization org where(p.organization = org.id) 并存在(从地址广告中选择 1zipcode = :zipcode 和 ad.organization = org.id)")

@Query("select p from Company p, Organization org where (p.organization = org.id) and exists ( select 1 from Address ad where zipcode = :zipcode and ad.organization = org.id)")

如何使用 JPA Criteria API 完成同样的事情?

How can the same thing be done using the JPA Criteria API?

推荐答案

这将使用内连接选择提供邮政编码的公司,这是您想要的吗?

This will select companies with provided zipcode using inner join, is this what you wanted?

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Company> cq = cb.createQuery(Company.class);
Root<Organization> root = cq.from(Organization.class);
Join<Organization, Address> adr = root.join("addresses");
cq.select(root.get("company"));
cq.where(cb.equal(adr.get("zipcode"), zipcode));

如果公司没有属性,您将无法通过组织访问公司.如果您的公司有对组织的引用,那么您可以将以下代码添加到组织类中,以进行单向映射到双向映射:

You won't be able to access Company via Organization, if it doesn't have a property for it. If your Company have a reference to Organization, then you can make unidirectional mapping to bidirectional mapping adding following code to Organization class:

@OneToOne(mappedBy="organization") //Providing the name of property in Company 
private Company company;

这篇关于如何将带有子查询的 JPQL 转换为等效的 Criteria API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆