Java 使用CriteriaBuilder在子查询中选择路径?

Java 使用CriteriaBuilder在子查询中选择路径?,java,jpa,jpql,criteria-api,Java,Jpa,Jpql,Criteria Api,如何使用CriteriaBuilder来构造表单SELECT a FROM e.attributes a….的子查询。。。。其中e是外部查询中引用的某个实体 我有一些实体类,它们涉及一个自由形式的键值结构,它提出了自己的问题,但这就是我所拥有的。我需要找到存在某些键值对的实体。我可以将其编写为以下形式的JPQL查询: 从实体e中选择e 其中e.type='foo' 并且存在从e.a属性中选择a 其中a.key='bar' 和a.value='baz' 对于固定查询字符串,我可以使用EntityM

如何使用CriteriaBuilder来构造表单SELECT a FROM e.attributes a….的子查询。。。。其中e是外部查询中引用的某个实体

我有一些实体类,它们涉及一个自由形式的键值结构,它提出了自己的问题,但这就是我所拥有的。我需要找到存在某些键值对的实体。我可以将其编写为以下形式的JPQL查询:

从实体e中选择e 其中e.type='foo' 并且存在从e.a属性中选择a 其中a.key='bar' 和a.value='baz' 对于固定查询字符串,我可以使用EntityManager.createQuery创建查询:

EntityManager em = /* ... */;
TypedQuery<Entity> tq = em.createQuery(queryString, Entity.class);

子查询上有许多关联方法,我想知道是否需要在外部查询中将实体与其属性连接起来,然后以某种方式进行关联,但我不确定从EE7 javadocs中,关联到底是做什么的,但关联确实返回一个from,这意味着我可以从中进行选择,这是很有希望的。

我最终在。第276页有一个相关查询的示例:

例4:一个特例 为了表达一些涉及单向关系的相关子查询,将子查询的域与包含查询的域相关联可能很有用。这是通过使用子查询接口的correlate方法执行的

例如:

CriteriaQuery<Customer> q = cb.createQuery(Customer.class);
Root<Customer> customer = q.from(Customer.class);
Subquery<Long> sq = q.subquery(Long.class);
Root<Customer> customerSub = sq.correlate(customer);
Join<Customer,Order> order = customerSub.join(Customer_.orders);
q.where(cb.gt(sq.select(cb.count(order)), 10))
.select(customer);
让我有一段时间不安的是,让我想到也许我的JPQL不合法,那就是从句p的语法。同一规范中的173如下所示:

我不清楚像e.attributes这样的东西怎么会是实体名称。事实证明,在子查询FROM子句的语法中实际上还有一个完整的其他产品,包括集合支持:

CriteriaQuery<Customer> q = cb.createQuery(Customer.class);
Root<Customer> customer = q.from(Customer.class);
Subquery<Long> sq = q.subquery(Long.class);
Root<Customer> customerSub = sq.correlate(customer);
Join<Customer,Order> order = customerSub.join(Customer_.orders);
q.where(cb.gt(sq.select(cb.count(order)), 10))
.select(customer);
from_clause ::=  FROM  identification_variable_declaration  ...
identification_variable_declaration ::= range_variable_declaration ...
range_variable_declaration ::= entity_name [AS] identification_variable
subquery_from_clause ::= FROM subselect_identification_variable_declaration ...
subselect_identification_variable_declaration ::=
  identification_variable_declaration |
  derived_path_expression [AS] identification_variable {join}* |
  derived_collection_member_declaration
derived_path_expression ::=
  superquery_identification_variable.{single_valued_object_field.}*collection_valued_field |
  superquery_identification_variable.{single_valued_object_field.}*single_valued_object_field