Connecting to a specific ON clause with JPA 2 Criteria API

Can I make one of the following queries with the JPA 2 API? Basically, there are a number of patterns that are used by profiles. Each user in the system has any number of profiles and two active ones. I would like to get ALL the templates and the number of users who own active profiles that use it.

Alternative 1

SELECT t.id, count(p.id)
FROM template t
LEFT JOIN profile p ON p.template_id = t.id
LEFT JOIN users u ON (u.active_profile_id = p.id OR u.active_personal_profile_id = p.id)
GROUP BY t.id

Alternative 2

SELECT t.id, count(p.id)
FROM COMPETENCE.template t
LEFT JOIN COMPETENCE.profile p ON (p.template_id = t.id)
LEFT JOIN users u1 on u1.active_profile_id = p.id
LEFT JOIN users u2 on u2.active_personal_profile_id = p.id
GROUP BY t.id

If I missed the requirement to get all the templates, I can just use User and Profile as Roots, and that would be enough:

CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<User> from = cq.from(User.class);
Root<Profile> from2 = cq.from(Profile.class);
Join<Profile, Template> join = from2.join(Profile_.template);
cq.where(cb.or(
             cb.equal(from.get(User_.activeCompetenceProfile), from2),
             cb.equal(from.get(User_.activePersonalProfile), from2)
));
cq.groupBy(join.get(Template_.id));
cq.multiselect(join.get(Template_.id), cb.count(from2.get(Profile_.id)));
List<Tuple> tuples = em.createQuery(cq).getResultList();

, , WHERE, , . 1 , ON , 2 , Root. , root . , , ON User, . , , .

, , , , , , .

+5

All Articles