JPA CriteriaBuilder与联结表

时间:2015-02-12 18:21:29

标签: java subquery jpa-2.0 criteria-api jointable

如何使用CriteriaBuilder表达下面的sql表达式?

select * from Ref where prac_id = (select prac_id from loc l join staff_loc sl where sl.loc = l.id and sl.pracstaff_id = 123)

模型类

@Entity
public class Ref {
    private Long id;
    private Prac prac;
}

@Entity
public class Loc {
    Long id;
    @ManyToOne
    Prac prac;
    @ManyToMany
    Set<PracStaff> pracStaff;
}

@Entity
public class Prac {
    Long id;
    @OneToMany
    Set<Loc> locs;
}

@Entity
public class PracStaff {
    Long id;
    @ManyToMany
    Set<Loc> locs;
}
  • 有一个将Loc映射到PracStaff的连接表;它有两列:pracstaff_id和loc_id
  • Loc只能属于一个Prac。

我想要获得的是使用CriteriaBuilder的所有具有ID为123的PracStaff的Ref对象。

1 个答案:

答案 0 :(得分:0)


这是我开始工作的解决方案,虽然我没有彻底测试过。使用

Expression<Collection<PracStaff>>

返回集合是我缺少的

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Ref> criteriaQuery = criteriaBuilder.createQuery(Ref.class);
Root<Ref> from = criteriaQuery.from(Ref.class);
criteriaQuery.select(from);

Subquery<Prac> subquery = criteriaQuery.subquery(Prac.class);
Root<Loc> fromLoc = subquery.from(Loc.class);
Expression<Collection<PracStaff>> pracStaffInLoc = fromLoc.get("pracStaff");
subquery.where(criteriaBuilder.isMember({pracStaffObj}, pracStaffInLoc));
subquery.select(fromLoc.<Prac>get("prac"));     
Path<Prac> specialist = from.get("{field in Ref class}");
Predicate p = criteriaBuilder.equal(specialist, subquery);