7

谁能给我一些关于如何将这种子查询放入的提示CriteriaQuery?(我正在使用JPA 2.0 - Hibernate 4.x

SELECT a, b, c FROM tableA WHERE a = (SELECT d FROM tableB WHERE tableB.id = 3)- 第二次选择总是得到一个结果或空值。

4

2 回答 2

14

尝试类似以下示例的方法来创建子查询:

CriteriaQuery<Object[]> cq = cb.createQuery(Object[].class);
Root tableA = cq.from(TableA.class);

Subquery<String> sq = cq.subquery(TableB.class);
Root tableB = cq.from(TableB.class);
sq.select(tableB.get("d"));
sq.where(cb.equal(tableB.get("id"), 3));

cq.multiselect(
    cb.get("a"),
    cb.get("b"),
    cb.get("c"));
cq.where(cb.equal(tableA.get("a"), sq));
List<Object[]> = em.createQuery(cq).getResultList();

请注意,由于附近缺少 IDE,该代码尚未经过测试。

于 2013-05-24T11:16:54.207 回答
0

您可以使用DetachedCriteria来表示子查询。您的代码应类似于:

DetachedCriteria subCriteria = DetachedCriteria.forClass(TableB.class);
subCriteria.add(Property.forName("id").eq(3)); //WHERE tableB.id = 3
subCriteria.setProjection(Projections.property("d")); // SELECT d from

DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClass());
criteria.add(Property.forName("a").eq(subCriteria)); //a = (sub-query)
criteria.setProjection(Projections.property("a"); //SELECT a
criteria.setProjection(Projections.property("b"); //SELECT b
criteria.setProjection(Projections.property("c"); //SELECT c
return getHibernateTemplate().findByCriteria(criteria);
于 2013-05-24T11:18:56.547 回答