title: How save a list of users to database with foreach loop using java
body: <p>I want to be able to send a list of users to my method, loop through each user and if user doesn't exist in database save it and if it exists throw an error.</p>
  <p>I have this code so far:</p>
  <pre><code>public List&lt;User&gt; addUsers(@RequestBody List&lt;User&gt; userList) {
          List&lt;User&gt; newUserList = new ArrayList&lt;&gt;();
          userList.forEach(
                  user -&gt; {
                     userRepository.findByEmail(user.getEmail())
                             .orElseThrow(() -&gt; new ResourceAlreadyExistsException(&quot;User with &quot;, &quot;email already exists.&quot;, user.getEmail()));
                      newUserList.add(user);
                  }
          );
          return userRepository.saveAll(newUserList);   
      }
  </code></pre>
  <p>But I am getting this error:</p>
  <pre><code>{
      &quot;timestamp&quot;: &quot;2021-10-06T16:50:52.476+00:00&quot;,
      &quot;status&quot;: 500,
      &quot;error&quot;: &quot;Internal Server Error&quot;,
      &quot;message&quot;: &quot;Query { \&quot;$java\&quot; : Query: { \&quot;email\&quot; : \&quot;domahaskins@gmail.com\&quot;}, Fields: {}, Sort: {} } returned non unique result.&quot;,
      &quot;path&quot;: &quot;/user&quot;
  }
  </code></pre>
  <p>What am I missing here?</p>