title: Spring data jpa querydsl projection with joins
body: <p>I'd like to optimize a queryDSL + Spring data query. Currently I am using a BooleanBuilder as the predicate, which would be fine, but it joins too many tables. I don't need all the columns from the tables and I don't need some of the tables at all. I believe using a projection would reduce the number of tables joined.</p>
  
  <p>I tried with using a Projections.bean() and also with extending MappingProjection, but both approaches result in not using joins but selecting from multiple tables which results in less rows than what's needed.</p>
  
  <p>My data structure consists of a Booking entity and some related entites like User, so looks something like the following:</p>
  
  <pre><code>@Entity
  public class Booking {
  
      @ManyToOne
      @JoinColumn(name = "userId", nullable = false)
      private User endUser;
  }
  
  @Entity
  public class User {
  
      @OneToMany(cascade = CascadeType.ALL, mappedBy = "endUser", fetch = FetchType.LAZY)
      private List&lt;Booking&gt; bookings;
  }
  </code></pre>
  
  <p>I implemented a custom queryDSL projection repository as described here: <a href="https://stackoverflow.com/questions/18300465/spring-data-jpa-and-querydsl-to-fetch-subset-of-columns-using-bean-constructor-p">Spring Data JPA and Querydsl to fetch subset of columns using bean/constructor projection</a></p>
  
  <p>I'm trying a projection like the following:</p>
  
  <pre><code>Projections.bean(Booking.class,
                   booking.uuid,
                   Projections.bean(User.class,
                                    booking.endUser.uuid
                   ).as(booking.endUser.getMetadata().getName()
  );
  </code></pre>
  
  <p>The sql generated by the current solution looks something like this:</p>
  
  <pre><code>select (...)
  from booking booking0_, 
       user user12_
  where booking0_.user_id=user12_.id
  </code></pre>
  
  <p>So, how can I make QueryDSL join the tables instead of selecting from all of them?
  Am I on the right path to try to optimize the query? Does the projection make sense?</p>