I have a rather simple SQL query where I need to get data from a Parent table based on a query on another Child table. For example:
Parent table:
ID NAME
-- ----
22 Frederick
26 James
39 Robert
Child table:
PARENT_ID NAME
--------- ----
22 Joey
22 Cindy
26 Robbie
39 Joe
So I need an SQL query like this that would get the names of any parents who have a child with a name like Joe - i.e., Frederick and Robert.
select NAME from PARENTS where ID in (
select PARENT_ID from CHILDREN where NAME like '%Joe%'
);
I'm trying something like this:
Subquery<Child> childSubquery = criteriaQuery.subquery(Child.class);
Root<Child> childRoot = childSubquery.from(Child.class);
Predicate likeChild = criteriaBuilder.like(childRoot.get(Child_.name), '%Joe%');
This would get me the children with names like Joe.
So how do I then get the parents of those children?
Based on this question, I tried like this:
CriteriaQuery<Parent> parentQuery = criteriaBuilder.createQuery(Parent.class);
Root<Parent> parentRoot = parentQuery.from(Parent.class);
parentQuery.select(parentRoot);
parentQuery.where(likeChild);
parentQuery.getResultList() <--- this method doesn't exist in CriteriaQuery!!