Union All and Sum with JPA CriteriaBuilder

后端 未结 4 1402
余生分开走
余生分开走 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:31

    Sorry the below example is not union, it is rather a join.

    I would consider using query with multiple roots.

    Here is an exerpt from Hiberante developer guide, the code is JPA 2.0-compatible.

    Criteria queries may define multiple roots, the effect of which is to create a cartesian product between the newly added root and the others. Here is an example matching all single men and all single women:

    CriteriaQuery query = builder.createQuery();
    Root men = query.from( Person.class );
    Root women = query.from( Person.class );
    Predicate menRestriction = builder.and(
            builder.equal( men.get( Person_.gender ), Gender.MALE ),
            builder.equal( men.get( Person_.relationshipStatus ), RelationshipStatus.SINGLE )
    );
    Predicate womenRestriction = builder.and(
            builder.equal( women.get( Person_.gender ), Gender.FEMALE ),
            builder.equal( women.get( Person_.relationshipStatus ), RelationshipStatus.SINGLE )
    );
    query.where( builder.and( menRestriction, womenRestriction ) )
    

提交回复
热议问题