如何将JPQL转换与子查询标准API相同呢? [英] How to convert a JPQL with subquery to Criteria API equivalent?

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

问题描述

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

Have a simple object model made up of 5 entities:


  1. 公司

  2. 组织

  3. 地址

  4. 俱乐部

  5. 集团


A公司与单个组织​​有关。 (组和俱乐部也与一个组织相关 - 这些都是单向的,这意味着组织中不包含它的主人的引用)。一个组织可以有0个或多个地址(ES)。

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

一个子查询可用于基于特定拉链code,这是一个地址的一个属性来访问公司的对象。
这里是可以与特定的拉链code访问这些公司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(从公司P,组织组织那里器选择p
  (p.organization = org.id)和存在(从地址的广告,其中选择1
  拉链code =:拉链code和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标准API做了什么?

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

推荐答案

本使用内部连接将选择与公司提供的拉链code,这是你想要的吗?

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

您将不能够通过组织访问公司,如果它不具有它的性质。如果你的公司要组织一个参考,那么你可以让单向映射,双向映射添加以下code到组织类:

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转换与子查询标准API相同呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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