Using CriteriaQuery for joining table with complex condition
<p>So far I implemented the following query:</p>

<pre><code>select distinct count(a.id)
from A a 
inner join B b 
  on a.id=b.b_id 
  and (
      b.name=?
  ) 
  /*and (
      b.created=(select max(created) from B where b_id = a.id)
  ) */
where a.x_id=?
</code></pre>

<p>What I need to implement is the part of <code>b.created=(select max(created) from B where b_id = a.id)</code>. Most of the examples I found, use incoming parameter for subquery, but I need to use the parent table connection.</p>

<pre><code>builder = entityManager.getCriteriaBuilder();
criteria = builder.createQuery();
a = criteria.from(A.class);
criteria
   .select(builder.count(a))
   .distinct(true);

Join&lt;A, B&gt; b = a.join("b");
b.on(
   builder.and(
      builder.equal(b.get("name"), "some")
   )
);
criteria.where(builder.equal(a.get("x"), x)));
</code></pre>