title: Select Query with Dynamic Columns in Spring Data JPA
body: <p>I have a requirement where the I receive the values from the Table A. 
  Here Table A stores column details of TableB.</p>
  
  <p>select columnList from TableA => Id1, Id2, Id3, Id4, Id5.. </p>
  
  <p>Using the result I need to query from Table B. </p>
  
  <p>Following are the cases</p>
  
  <ol>
  <li><p>Select Id1, Id2, Id3 from TableB.</p></li>
  <li><p>Select Id4, Id5 from TableB.</p></li>
  <li><p>Select Id6, Id7, Id8 from TableB.</p></li>
  </ol>
  
  <p>Like this case will grow. I would like to know how to achieve this one in Spring Data JPA.
  It is something like dynamic projections in Spring Data JPA. </p>
  
  <p>Note: Column Names stored in TableA is used in the TableB.</p>
  
  <p>Reason: If I could able to achieve this, it would be easy to pull the data which only what I need.</p>
  
  <p>Need to know, whether we can acheive this in Spring Data JPA or Not? If possible, then how we can.</p>
  
  <p>Can we use CriteriaQuery and CriteriaBuilder.???
  Based on the number of column passed, the select query will construct with those values passed in the method call. I can pass that as list and fetch the results from this method call. entityManager.createQuery(criteriaQuery).getResultList();</p>
  
  <p>I need a better solution than this. </p>
  
  <pre><code>public void getTableBValues(final List&lt;String&gt; columnList) {
  
      final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();        
      final CriteriaQuery&lt;Tuple&gt; criteriaQuery = criteriaBuilder.createTupleQuery();
      final Root&lt;TableB&gt; root = criteriaQuery.from(TableB.class);
  
      // Construct the Selection List to get required columns from TableB
      final List&lt;Selection&lt;?&gt;&gt; pathList = columnList.stream().map(p -&gt; {
          final Selection&lt;Object&gt; path = root.get(p);
          return path;
      }).collect(Collectors.toList());
  
      criteriaQuery.multiselect(pathList);
      // result will be stored in the result list. 
      final List&lt;Tuple&gt; resultList = entityManager.createQuery(criteriaQuery).getResultList();
      entityManager.close();
  
  }
  </code></pre>