如何使用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;
}
我想要获得的是使用CriteriaBuilder的所有具有ID为123的PracStaff的Ref对象。
答案 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);