Union All and Sum with JPA CriteriaBuilder

后端 未结 4 1340
余生分开走
余生分开走 2021-02-06 09:06

I am trying to convert a native SQL query to use the Criteria API in JPA 2.0. I have found a lot of Criteria API examples on Google, but I am having a really hard time putting

4条回答
  •  鱼传尺愫
    2021-02-06 09:30

    As Marcin noted it is possible with inheritance, at least in special cases.

    If you can make queried entities inherit one from another using TABLE_PER_CLASS inheritance strategy (provided optionally, possible in hibernate, but has limitations there - you cannot use IDENTITY and AUTO) and if the field to be present in the query has the same name in both entities then you can unite both entities by querying the parent one.

    For instance, if entity class Child extends from entity class Parent both having field "name", query would be :

    select p.name from Parent p

    To select only names of Parent entities add condition with TYPE.

    select p.name from Parent p where TYPE(p) = Parent

    If modifying entities to inherit one from another is inappropriate, you can create special ones (with inheritance, of cause) for this query, since it is possible to create several entities for the same table. But you likely don't find that effort reasonable.

提交回复
热议问题