JPA 2.0 CriteriaBuilder:SELECT FROM ... IN

时间:2017-09-12 08:31:19

标签: java jpa jpa-2.0 criteria

我想使用JPA 2.0 CriteriaBuilder创建以下SQL查询:

SELECT * FROM PROFIL WHERE PROFILID IN (SELECT PROFILID FROM ROLEPROFIL WHERE ROLEID = roleId)

以下是我的课程:

Profil:

public class Profil extends AbstractDomain<Long> {

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idgen_x")
    @UiInfo(name = "Identifiant")
    private Long profilId;

    @Column(nullable = false)
    @UiInfo(name = "Libellé")
    private String lib;

}

角色:

public class Role extends AbstractDomain<Long> {
    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idgen_x")
    @UiInfo(name = "Identifiant")
    private Long roleId;
}

RoleProfil:

public class RoleProfil extends AbstractDomain<Long> {
    @Id
    @Column
    @UiInfo(name = "Identifiant")
    private Long roleProfilId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = false)
    @UiInfo(name = "Profil")
    private Profil profilId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = false)
    @UiInfo(name = "Rôle")
    private Role roleId;

}

我想要做的是使用JPA创建一个Profils ID Role的函数。

这就是我的开始,但我是JPA的新手,我无法弄清楚如何做到这一点:

public List<Profil> findProfilsByRoleId(Long roleId) {
        final CriteriaBuilder builder = getCriteriaBuilder();
        final CriteriaQuery<Profil> criteriaQuery = builder.createQuery(Profil.class);
        final Root<Profil> from = criteriaQuery.from(Profil.class);

        //TODO

        TypedQuery<Profil> query = getEntityManager().createQuery(criteriaQuery);
        return query.getResultList();

    }

我该怎么做?

1 个答案:

答案 0 :(得分:1)

SELECT  PF.* 
FROM PROFIL AS PF
INNER JOIN ROLEPROFIL AS RPF
ON RPF.PROFILID = PF.PROFILID 
WHERE RPF.ROLEID = {roleId}

可能更容易实现查询。我认为java中的代码可能是这样的(我还没有测试过刚才提出的解决方案):

public List<Profil> findProfilsByRoleId(Long roleId) {
    final CriteriaBuilder builder = getCriteriaBuilder();
    final CriteriaQuery<Profil> query = builder.createQuery(Profil.class);
    final Root<RoleProfil> from = query.from(RoleProfil.class);

    query.select(from.get(RoleProfil_.profilId));
    query.where(builder.equal(from.get(RoleProfil_.roleId).get(Role_.roleId), roleId));

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

}