0

Based on this answer https://stackoverflow.com/a/2111420/3989524 I first created a working SQL:

SELECT d.*
FROM device d
LEFT OUTER JOIN installation_record ir1 ON (d.id = ir1.device)
LEFT OUTER JOIN installation_record ir2 ON (d.id = ir2.device AND ir1.install_date < ir2.install_date)
WHERE ir2.id IS NULL AND ir1.uninstall_date IS NULL;

and then a criteria query which looks to produce an equivalent HQL (in the end), but Hibernate throws an error:

org.hibernate.hql.internal.ast.QuerySyntaxException: with-clause referenced two different from-clause elements

The HQL from the error message:

SELECT generatedAlias0 FROM Device AS generatedAlias0 
LEFT JOIN generatedAlias0.installationRecordList AS generatedAlias1 
LEFT JOIN generatedAlias0.installationRecordList AS generatedAlias2 
WITH generatedAlias1.installDate<generatedAlias2.installDate 
WHERE ( generatedAlias2.id IS NULL ) AND ( generatedAlias1.uninstallDate IS NULL )

The criteria query:

final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<Device> cq = cb.createQuery(Device.class);
final Root<Device> root = cq.from(Device.class);
final Join<Device, InstallationRecord> join1 = root.join(Device_.installationRecordList, JoinType.LEFT);
final Join<Device, InstallationRecord> join2 = root.join(Device_.installationRecordList, JoinType.LEFT);

join2.on(cb.lessThan(join1.get(InstallationRecord_.installDate), join2.get(InstallationRecord_.installDate)));
cq.select(root);

final List<Predicate> predicates = Lists.newArrayList();
predicates.add(cb.isNull(join2.get(InstallationRecord_.id)));
predicates.add(cb.isNull(join1.get(InstallationRecord_.uninstallDate)));
cq.where(predicates.toArray(new Predicate[] {}));

return em.createQuery(cq).getResultList();

Is there anyway to get what I want or there no other way around some internal hibernate bug.

Community
  • 1
  • 1
  • I wonder is it related to some limitation of `on` method. have you tried move your predicate to `where` statement? – user902383 May 17 '16 at 12:10

1 Answers1

-1

Maybe:

final Join<InstallationRecord, InstallationRecord> join2 = root.join(InstallationRecord_.id, JoinType.LEFT);

because ON (d.id = ir2.device AND is missing in the HQL.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146