Home » Java » How to filter/order by pivoted value using JPA criteria API?

How to filter/order by pivoted value using JPA criteria API?

Posted by: admin September 26, 2018 Leave a comment

Questions:

Let’s say we have such entities (skipping getters/setters, visibility parameters, annotations etc.)

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

I want to select all distinct TargetEntities that simultaniously (by and):

  1. Have attribute value equal to A where attribute type code equal to X (if entity do not have attribute with such code at all, it should not pass this criteria)
  2. Have attribute value not equal to B where attribute code is equal to Y (if entity do not have attribute with such code at all, it should pass this criteria)

and order them by attribute value where attribute code is equal to Z (absence of such attribute should be considered as null value).

I have to use JPA criteria API for this and I can’t add any views to DB.

Could anyone explain this pivoting-related usage of criteria API?

UPD: sql query for similar select would look approximately like this:

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
Answers: