2

我有 3 个名为 School、SchoolType 和 Country 的表。您可以看到 School 和 SchoolType 之间的关系。我要查询的是;

选择与至少有一所名为“blabla”的学校的学校类型具有相同 ID 的国家/地区。

我的学校班级;

@JoinColumn(name = "school_type_ref", referencedColumnName = "school")
@ManyToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER)
private SchoolType schooltype;

我的 SchoolType 类;

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "schooltype")
private List<School> schoolList;

private String id;

我的国家班;

private String id;
4

1 回答 1

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),但它对我永远不起作用。

我的答案是基于JPA 2.0、Criteria API、子查询、In Expressions

于 2013-09-06T13:00:03.827 回答