title: How to select on max(id) from sub-query in Hibernate Specification?
body: <p>I have the following code that generates the correct query, except that one table name is missing in the sql.</p>
  
  <pre><code>public List&lt;Correspondence&gt; findThreads(String userId, int page, int resultsPerPage) {
      Specification&lt;Correspondence&gt; spec = Specifications.&lt;Correspondence&gt;where((cor, query, cb) -&gt; {
          Root&lt;UserRegisterPerson&gt; ur = query.from(UserRegisterPerson.class);
          Root&lt;Correspondence&gt; cor2 = query.from(Correspondence.class);
          return cb.and(
                  cb.equal(ur.get("registerPersonNr"), cor.get("registerPersonNr")),
                  cb.equal(ur.get("userId"), userId),
                  cb.equal(cor.get("id"),
                // problem:
                  query.subquery(Number.class).select(cb.max(cor2.get("id"))).where(cb.and(
                          cb.equal(cor2.get("applicationNumber"), cor.get("applicationNumber")),
                          cb.equal(cor2.get("dossierType"), cor.get("dossierType")),
                          cb.equal(cor2.get("registerPersonNr"), cor.get("registerPersonNr"))))));
      });
      return this.correspondenceRepository.findAll(spec, new PageRequest(page, resultsPerPage)).getContent();
  }
  </code></pre>
  
  <p>Generated SQL with the missing table name</p>
  
  <pre><code>select generatedAlias0
  from 
      nl.boip.correspondencemodule.commons.database.entities.Correspondence as generatedAlias0, 
      nl.boip.correspondencemodule.commons.database.entities.UserRegisterPerson as generatedAlias1, 
      # the next line should actually be further below, where the table name is missing.
      nl.boip.correspondencemodule.commons.database.entities.Correspondence as generatedAlias2
  where
      ( generatedAlias1.registerPersonNr=generatedAlias0.registerPersonNr ) 
      and ( generatedAlias1.userId=:param0 )
      and ( generatedAlias0.id=(
          select max(generatedAlias2.id)
          # See next line, the table name is missing
          from  where (
              generatedAlias2.applicationNumber=generatedAlias0.applicationNumber ) 
              and (generatedAlias2.dossierType=generatedAlias0.dossierType )
              and ( generatedAlias2.registerPersonNr=generatedAlias0.registerPersonNr )) )
  </code></pre>
  
  <p>My real case is more complicated, so I can't use CrudRepository for this query (because the sort field is actually a parameter in my rest-call)</p>