artaxerxe
artaxerxe

Reputation: 6411

Subquery in where clause with CriteriaQuery

Can anybody give me some hints on how to put that kind of subquery in a CriteriaQuery? (I'm using JPA 2.0 - Hibernate 4.x)

SELECT a, b, c FROM tableA WHERE a = (SELECT d FROM tableB WHERE tableB.id = 3) - the second select will always get a single result or null.

Upvotes: 7

Views: 27217

Answers (2)

Menno
Menno

Reputation: 12621

Try something like the following example to create a subquery:

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();

Note the code has not been tested due to the lack of an IDE nearby.

Upvotes: 14

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You can use DetachedCriteria to represend the sub-query. Your code should look something like:

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);

Upvotes: 0

Related Questions