title: Spring boot fetch database data for multiple IDs using single call
body: <p>In spring boot project I have following code which cause low performance as several database calls happen inside a loop which is a bad practice.</p>
  <pre><code>userList.forEach(user -&gt; {
       List&lt;Project&gt; userProjectsList = ProjectRepository.findByUser_UserIdOrderByDatecompletedDesc(user.getUserId());
  }
  </code></pre>
  <p><strong>Note:</strong> userList is a List returned from a stored procedure.
  Project is an entity. Relevant repository for that entity is ProjectRepository.
  User is also an entity.
  Project and User entity has <strong>many to one</strong> relationship.</p>
  <p>Project Entity is like below;</p>
  <pre><code>@Entity
  @Table(name = &quot;Project&quot;)
  public class Project {
    @Id
    @GeneratedValue
    private Integer projectid;
    private Calendar datecompleted;
    @ManyToOne
    @JoinColumn(name = &quot;userid&quot;, referencedColumnName = &quot;userid&quot;)
    private User user;
  
  // getters and setters
  }
  </code></pre>
  <p>I need to modify this code to be more efficient. As a solution I'm planning to fetch all projects belongs to all users <strong>at once</strong> from database. (Mysql database is using)</p>
  <p>I tried with below code but seems it's not correct.</p>
  <pre><code>List&lt;Integer&gt; userIdList = UserList.stream().map(User::getUserId).collect(Collectors.toList());
  List&lt;List&lt;Project&gt;&gt; userProjectsList = ProjectRepository.findByUser_UserIdInOrderByDatecompletedDesc(userIdList);
  </code></pre>
  <p>Following method is in ProjectRepository.</p>
  <pre><code>List&lt;List&lt;Project&gt;&gt; findByUser_UserIdInOrderByDatecompletedDesc(List&lt;Integer&gt; userIdList);
  </code></pre>
  <p>Kindly support me to find a better solution for this. Thanks in advance</p>
  <p><strong>Update:</strong></p>
  <p>Above code is not returning the correct result. I passed 2 userIds. Out of them one user has 2 projects and the other user has 1 project.
  Expected result is:</p>
  <pre><code>[0]-&gt;[0]:project1, [1]:project2
  [1]-&gt;[0]:project3
  </code></pre>
  <p>But, returned result is:</p>
  <pre><code>[0]-&gt;[0]:project1
  [1]-&gt;[0]:project2
  [2]-&gt;[0]:project3
  </code></pre>