eclipselinkjpqltoplink

EclipseLink/TopLink full outer join instead left join


On model Card can have or not CardHolder ( 1:1 ), and I would like getting every cards filter by issuer linked to actived cardHolders plus cards without cardHolders, so I need a full outer join. Although the query below translate to left join returning just cards with cardHolders

    final ExpressionBuilder builder = new ExpressionBuilder( Card.class );

    Expression queryExp = builder.get( "cardIssuer" ).equal( cardIssuer );
    queryExp = queryExp.and( builder.get( "cardStatus" ).get( "statusType" ).equal( "ACTIVATED" ) );
    queryExp = queryExp.and( builder.getAllowingNull( "cardHolder" )isNull().or(
                  builder.get( "cardHolder" ).get( "status" ).get( "status" ).equal( "ACTIVE" ) ) );


    Expression orderExpression = builder.get( "cardHolder" ).get( "surname" ).descending();


    return getMultiple( queryExp, pageable , Card.class, orderExpression );

Translate query is

  SELECT COUNT(t0.CARD_ID) FROM CARD t0 LEFT JOIN CARD_HOLDER t3 
 ON (t3.CARD_HOLDER_ID = t0.CARD_HOLDER_ID), CARD_HOLDER_STATUS t2, CARD_STATUS t1 
 WHERE (((((t0.CARD_ISSUER_ID = 10006) AND (t1.STATUS_TYPE = 'ACTIVATED')) AND (t2.STATUS = 'ACTIVE')) 
 AND (t0.CARD_ID IN ('52683','52692'))) 
 AND ((t1.CARD_STATUS_ID = t0.CARD_STATUS_ID) AND (t2.STATUS_ID = t3.STATUS_ID)))

Solution

  • Due to JPA version the outer join is not properly done, so I found a way through native queries

    @NamedNativeQueries( {
    @NamedNativeQuery( name = Card.USER_DIRECTORY_BASE,
        query = "select * from card c full outer join card_holder ch on c.card_holder_id = ch.card_holder_id "
          + "where c.CARD_ISSUER_ID = ?1 and c.card_status_id = 1 and ( ch.STATUS_ID = 1 or c.CARD_HOLDER_ID is null) "
          + "order by ch.FORENAME asc", 
        resultClass  = Card.class ),
    
    @NamedNativeQuery( name = Card.USER_DIRECTORY_BASE_COUNT,
        query = "select count(*) from card c full outer join card_holder ch on c.card_holder_id = ch.card_holder_id "
          + "where c.CARD_ISSUER_ID = ?1 and c.card_status_id = 1 and ( ch.STATUS_ID = 1 or c.CARD_HOLDER_ID is null) "
          + "order by ch.FORENAME asc" )
    } )
    

    And getting results

    Query query = em.createNamedQuery( Card.USER_DIRECTORY_BASE);
    query.setParamenter(1,10000);
    query.getResultList();