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)
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());
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.