使用JPA条件api进行右连接

时间:2017-10-05 12:51:54

标签: java jpa criteria

我正在尝试使用jpa标准api实现此SQL查询:

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

也可以写成:

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

这就是我的尝试:

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

但它不起作用,我在此行中收到以下错误: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>)

我该如何解决这个问题?

更新

这些是我的实体:

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

更新2:

似乎jpa条件api不支持RIGHT JOIN,因此可以使用第二个查询来完成。

1 个答案:

答案 0 :(得分:0)

 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.