title: How can I improve the response speed of request with a projection in Spring Data JPA?
body: <p>I have a goal repository that returns a list Goals based on a competition: </p>
  
  <pre><code>public interface GoalRespository extends JpaRepository&lt;Goal,Long&gt; {
  
      @Query(value = "SELECT * FROM goal g " +
              "JOIN matches m ON g.goal_match = m.idmatch " +
              "JOIN competitions c ON m.competition = c.idcompetitions " +
              "WHERE c.idcompetitions = ?1", nativeQuery = true)
      List&lt;Goal&gt; findGoalsByCompetition(@Param ("competition") Long competition);
  
  }
  </code></pre>
  
  <p>And then I have a Projection for my Goal Class that return the Player that scored the goal inline: </p>
  
  <pre><code>@Projection(name = "goalInlinePlayers", types = { Goal.class })
  public interface GoalInlinePlayers {
  
      Long getIdgoal();
      Long getGoalMinute();
      Long getGoalSeconds();
      Player getGoalPlayer();
  }
  </code></pre>
  
  <p>So my problem is that if I do a GET call to the endpoint without the projection </p>
  
  <blockquote>
    <p>/goals/search/findGoalsByCompetition?competition=219</p>
  </blockquote>
  
  <p>the response takes lest than a second, if I add the projection to my query params</p>
  
  <blockquote>
    <p>/goals/search/findGoalsByCompetition?competition=219&amp;projection=goalInlinePlayers</p>
  </blockquote>
  
  <p>It takes around 12 seconds to resolve. 
  Also, for some display purposes I need to add assists and teams to my projection, in which case it takes 20 seconds. </p>
  
  <p><strong>Some extra data:</strong></p>
  
  <ul>
  <li>The example that takes that time has 350 goals. </li>
  <li>I have the exact same thing to return matches from a competition with a projection to inline the home and away team objects and it takes 1.5 seconds. </li>
  <li>The teams table have 150 records while the players table have around 2000. (Not sure if related)</li>
  </ul>
  
  <p>Any thoughts on why is it taking so long to resolve a request with a projection or where is the bottleneck?</p>