title: Spring Data JPA Query - class projection containing another custom object
body: <p>Suppose I have a <code>Foo</code> entity (fields: <code>id</code>, <code>name</code> and <code>barId</code>) and a <code>Bar</code> entity (fields: <code>id</code>, <code>age</code>), in a one-to-many relation. I want to select all the <code>Foo</code>s, having the corresponding Bar <code>age</code> attached.</p>
  <p>I see 2 options, but none seems to work:</p>
  <ol>
  <li>The so-called <a href="https://I%20need%20to%20select%20a%20complete%20object%20and%20one%20more%20field%20from%20the%20database%20(using%20a%20join%20on%20the%201-n%20relation)%20using%20Spring%20Data%20JPA%20@Query." rel="nofollow noreferrer">closed projection approach</a></li>
  </ol>
  <pre><code>@Query(&quot;select f as foo, b.age as age from Foo f inner join Bar b on f.barId = b.id&quot;)
  List&lt;FooWithAge&gt; query1();
  </code></pre>
  <p>where FooWithAge is an <strong>interface</strong> having as methods <code>Foo getFoo()</code> and <code>Integer getAge()</code>;</p>
  <ol start="2">
  <li>The so-called <a href="https://I%20need%20to%20select%20a%20complete%20object%20and%20one%20more%20field%20from%20the%20database%20(using%20a%20join%20on%20the%201-n%20relation)%20using%20Spring%20Data%20JPA%20@Query." rel="nofollow noreferrer">class projection approach</a></li>
  </ol>
  <pre><code>@Query(&quot;select new FooWithAge(new Foo(f), b.age) from Foo f inner join Bar b on f.barId = b.id&quot;)
  List&lt;FooWithAge&gt; query2();
  </code></pre>
  <p>where FooWithAge is a <strong>class</strong> having as fields <code>Foo foo</code> and <code>Integer age</code> and a <em>constructor that takes these 2 as parameters.</em></p>
  <p>None of these solutions seem to work. A third solution, of taking all the fields of Foo as parameters of the constructor of FooWithAge works, but I would like to find a cleaner solution.</p>
  <p>Note: I cannot use anything else than vanilla Spring Data JPA queries. Native queries are excluded.</p>