0

I have 2 tables say Parent and Child and they are one-to-many relationships.

In the entity classes, the Parent class has a list of Child objects.

So if using JPA query, how can I write a query to retrieve all Parent(s) and their last child?

There may be a case that a Parent does not have a child.

If using sql, it would be like:

select * from parent p 
  left outer join child c on c.parent_id = p.id 
where c.child_id is null 
   or c.child_id = ( 
select child_id from ( 
select child_id  
  from child d 
 where d.parent_id = p.id order by child_age DESC, child_id DESC) 
where rownum<=1)
Dicky Ho
  • 35
  • 6

2 Answers2

-1

You can use CriteriaBuilder obtain from EntityManager, then obtain CriteriaQuery from it. I am assuming Parent Entity here as Teacher and Child entity as Phone. Below code is to fetch all the phones numbers by teacher firstName.

  CriteriaBuilder cb = em.getCriteriaBuilder();
  CriteriaQuery<Phone> query = cb.createQuery(Phone.class);
  Root<Teacher> teacher = query.from(Teacher.class);
  Join<Teacher, Phone> phones = teacher.join("phones",JoinType.LEFT);
  query.select(phones).where(cb.equal(teacher.get("firstName"), "prasad"));

List<Phone> results = em.createQuery(query).getResultList();
for (Phone phone : results) {
    System.out.println("Number = " + phone.getNumber() + " "
        + "Type = " + phone.getType());
}
Gaurav Srivastav
  • 2,381
  • 1
  • 15
  • 18
  • this clearly won't work, a left join is needed in cases where there is none in the other side 1....[0-*] – FiruzzZ Jun 29 '18 at 03:40
-1

solving this in one JPQL (or CriteriaQuery) would be very ugly, retrieving 2 objects instances like

SELECT p, lastChild FROM Parent p LEFT JOIN p.children c

u can't either subquery in select

SELECT p, (SELECT c FROM Child c where c.parent = p ORDER BY c.age DESC) FROM Parent p

the simplest solution would be: get all the parent, then look for the older child

FiruzzZ
  • 661
  • 1
  • 6
  • 21