我有3个名为School,SchoolType和Country的表。您可以看到School和SchoolType之间的关系。我想要查询的是;
选择与学校类型具有相同ID的国家/地区至少有一所名为“blabla”的学校。
我的学校班级;
@JoinColumn(name = "school_type_ref", referencedColumnName = "school")
@ManyToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER)
private SchoolType schooltype;
My SchoolType Class;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "schooltype")
private List<School> schoolList;
private String id;
我的国家班级;
private String id;
答案 0 :(得分:1)
检查一下:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Country> c = cb.createQuery(Country.class);
Root<Country> countries = c.from(Country.class);
Subquery<Integer> sq = c.subquery(Integer.class);
Root<SchoolType> schoolTypes = sq.from(SchoolType.class);
sq.select(schoolTypes.<Integer>get("id")).where(
cb.equal(schoolTypes.get("schoolList").get("name"), "blabla"));
c.select(countries).where(cb.in(countries.<Integer>get("id")).value(sq));
TypedQuery<Country> q = entityManager.createQuery(c);
List<Country> result = q.getResultList();
也可以尝试使用schoolTypes.<Integer>get("id")
代替schoolTypes.get(SchoolType_.id)
,但它永远不适合我。