简体   繁体   中英

Right join using JPA criteria api

I'm trying to implement this sql query using jpa criteria api :

SELECT F.* FROM PF right join F on F.FID = PF.FID WHERE PF.PFID is null;

Which also can be written as:

SELECT F.* FROM F left join PF on F.FID = PF.FID WHERE PF.FID is null;

This is what I tried:

public List<F> listFWithoutP() {
    final CriteriaBuilder builder = getCriteriaBuilder();
    final CriteriaQuery<F> query = builder.createQuery(F.class);
    final Root<PF> from = query.from(PF.class);

    Join<PF, F> join = from.join(PF_.f, JoinType.RIGHT);

    query.select(join.get(PF_.f))
            .where(builder.isNull(from.get(PF_.pFId)));

    final TypedQuery<F> typedQuery = getEntityManager().createQuery(query);
    return typedQuery.getResultList();
}

But it doesn't work, I get the following error in this line : query.select(join.get(PF_.f))

The method get(SingularAttribute<? super F,Y>) in the type Path<F> is not applicable for the arguments (SingularAttribute<PF,F>)

How can I solve this ?

Update:

These are my entities :

    public class F extends AbstractDomain<Long> {

        @Id
        @Column
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idgen")
        private Long fId;

        @Column(nullable = false)
        private String lib;
    }

public class PF extends AbstractDomain<Long> {

    @Id
    @Column
    private Long pFId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = false)
    private P p;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = false)
    private F f;
}

Update 2:

It seems like RIGHT JOIN is not supported by the jpa criteria api, so this can be done using the second query.

 final Session session = entityManager.unwrap(Session.class);
        final Criteria criteria = session.createCriteria(PF.class, "pf")
                .createAlias("pf.f", "f")
 .add(Restrictions.eqProperty("pf.pFId",
                        "f.fId"))
.add(Restrictions.isNull("pf.pFId"));

Hello Aimad,
please try this criteria query and let me know if that works,this criteria would exactly replicate your SQL query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM