首页 > 解决方案 > 如何使用 JPA 标准 API 按透视值过滤/排序?

问题描述

假设我们有这样的实体(跳过 getter/setter、可见性参数、注释等)

class TargetEntity {
 Integer id;
 List <Attribute> attributes;// one to many
 }

class Attribute {
 Integer id;
 AttributeType type;//many to one
String value;
}

class AttributeType{
Integer id;
String code;
String description;
}

我想同时(通过和)选择所有不同的 TargetEntities:

  1. 具有等于​​ A 的属性值,其中属性类型代码等于 X(如果实体根本没有具有此类代码的属性,则不应通过此标准)
  2. 具有不等于 B 的属性值,其中属性代码等于 Y(如果实体根本没有具有此类代码的属性,则应通过此标准)

并按属性值对它们进行排序,其中属性代码等于 Z(不存在此类属性应视为空值)。

我必须为此使用 JPA 标准 API,并且无法向数据库添加任何视图。

谁能解释标准 API 的这种与旋转相关的用法?

UPD:类似选择的 sql 查询大致如下所示:

select tet.* from target_entity_table tet
left join (
select attr.target_entity_table_id as hid, attr_type.code as code, attr.attribute_value as value from attribute_table attr 
inner join attribute_type_table attr_type on attr.attribute_id = attr_type.id
) X on X.hid = tet.id and X.code = 'X'
left join (
select attr.target_entity_table_id as hid, attr_type.code as code, attr.attribute_value as value from attribute_table attr 
inner join attribute_type_table attr_type on attr.attribute_id = attr_type.id
) Y on Y.hid = tet.id and Y.code = 'Y'
left join (
select attr.target_entity_table_id as hid, attr_type.code as code, attr.attribute_value as value from attribute_table attr 
inner join attribute_type_table attr_type on attr.attribute_id = attr_type.id
) Z on Z.hid = tet.id and Z.code = 'Z'
where x.value = 'A' and Y.value != 'B'
order by z.value asc

标签: javajpacriteria-api

解决方案


推荐阅读