我遇到了关于JPA-2.0查询与关系的问题。如何用Dataset
选择至少一个Event
的任何type = B
?
@Entity
class Dataset {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "dataset")
public List<Event> events;
}
@Entity
class Event {
@ManyToOne
@JoinColumn
public Dataset dataset;
public Type type;
}
enum Type {
A, B, C
}
我的出发点是
CriteriaBuilder _builder = em.getCriteriaBuilder();
CriteriaQuery<Dataset> _criteria = _builder.createQuery(Dataset.class);
// select from
Root<Dataset> _root = _criteria.from(Dataset.class);
_criteria.select(_root);
// apply some filter as where-clause (visitor)
getFilter().apply(
_root, _criteria, _builder, em.getMetamodel()
);
// how to add a clause as defined before?
...
对此有任何想法。我试图创建一个子查询以及一个连接,但我在某种程度上做错了,并且总是得到所有数据集。
答案 0 :(得分:4)
尝试
SELECT d FROM DataSet d WHERE EXISTS
(SELECT e FROM Event e WHERE e.dataSet = d and e.type = :type)
编辑:正如Pascal指出的那样,您似乎正在使用Criteria API。不熟悉这个,但我会有一个刺。
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Dataset> criteria = builder.createQuery(Dataset.class);
Root<Dataset> root = criteria.from(Dataset.class);
criteria.select(root);
// build the subquery
SubQuery<Event> subQuery = criteria.subQuery(Event.class);
Root<Event> eventRoot = subQuery.from(Event.class);
subQuery.select(eventRoot);
ParameterExpression<String> typeParameter = builder.parameter(String.class);
Predicate typePredicate = builder.equal(eventRoot.get(Event_.type), typeParameter));
// i have not tried this before but I assume this will correlate the subquery with the parent root entity
Predicate correlatePredicate = builder.equal(eventRoot.get(Event_.dataSet), root);
subQuery.where(builder.and(typePredicate, correlatePredicate);
criteria.where(builder.exists(subQuery)));
List<DataSet> dataSets = em.createQuery(criteria).getResultList();
这是一项艰苦的工作。我现在要回Linq了。