title: Spring JPA query using specification and projection
body: <p>I used spring jpa specification to build dynamically an entity query.</p>
  
  <p>It's working perfect but the query returns all entity fields which makes the performance slower. 
  I want to fetch specific entity fields only and not fetching all entity fields and dependencies which I don't want and I will not use.</p>
  
  <p>I search on the web, I tried some scenarios but without any lack.
  Can anyone suggest any solution on this?</p>
  
  <p>Thanks in advance</p>
  
  <p>Here is what I have.I'm using spring boot 2.2.4</p>
  
  <pre><code>public class Concert {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;
  
      @Column
      private String name;
  
      @Column
      private String code;
  
      @Column
      private double totalIncome;
  
      @Column            
      private double totalExpenses;
  
      @Column
      private double totalBudget;
  
      @ManyToOne(targetEntity = Orchestra.class, fetch = FetchType.EAGER, optional = false)
      @JoinColumn(name = "orchestra_id")
      private Orchestra orchestra;
  
      @ManyToOne(targetEntity = ConcertStatus.class, fetch = FetchType.EAGER, optional = false)
      @JoinColumn(name = "concert_status_id")
      private ConcertStatus status;
  
      /* other fields */
  
  }
  </code></pre>
  
  <p>Specification:</p>
  
  <pre><code>public class ConcertSpecification implements Specification&lt;Concert&gt; {
  
      @Override
      public Predicate toPredicate(Root&lt;Concert&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder builder) {
          List&lt;Predicate&gt; predicates = new ArrayList&lt;&gt;();
  
          //add add criteria to predicates
          for (Criterion criteria : criteriaList) {
  
              /* predicates builder here */
          }
  
          return builder.and(predicates.toArray(new Predicate[0]));
      }
  }
  </code></pre>
  
  <p>Repository:</p>
  
  <pre><code>public interface ConcertDao extends JpaRepository&lt;Concert, Long&gt;, JpaSpecificationExecutor&lt;Concert&gt;, PagingAndSortingRepository&lt;Concert, Long&gt; { }
  </code></pre>
  
  <p>ConcertService:</p>
  
  <pre><code>public interface ConcertService {
      Page&lt;Concert&gt; findAll(@Nullable Specification&lt;Concert&gt; spec, Pageable pageable); 
  }   
  </code></pre>
  
  <p>ConcertServiceImpl:</p>
  
  <pre><code>@Service(value = "concertService")
  public class ConcertServiceImpl implements ConcertService {
  
      public Page&lt;Concert&gt; findAll(@Nullable Specification&lt;Concert&gt; spec, Pageable pageable){
          List&lt;Concert&gt; list = new ArrayList&lt;&gt;();
          concertDao.findAll(spec).iterator().forEachRemaining(list::add);
          return new PageImpl&lt;Concert&gt;(list);
      }
  }   
  </code></pre>