title: Check existence in Doctrine for persisted and not persisted entities
body: <p>My question could be a duplicate of <a href="https://stackoverflow.com/questions/7877987/read-objects-persisted-but-not-yet-flushed-with-doctrine">this one</a>, but I can't find any satisfying answer so I will try to make this one more precise. </p>
  
  <p>I am building an import service from an other API. And I don't want any duplicate in my new database. </p>
  
  <p>So here an example of my current implementation:</p>
  
  <p>The Controller: </p>
  
  <pre><code>public function mainAction () 
  {
      $em = $this-&gt;getDoctrine()-&gt;getManager();
  
      $persons_data = [
          [
              'first_name' =&gt; 'John',
              'last_name' =&gt; 'Doe'
          ],
          [
              'first_name' =&gt; 'John',
              'last_name' =&gt; 'Doe'
          ]
      ];
  
      $array = [];
  
      foreach($persons_data as $person_data) 
      {
          $person = $this-&gt;get('my_service')-&gt;findOrCreatePerson($person_data);
          $array[] = $person;
      }
  
      $em-&gt;flush();
  
      return new Response();
  }
  </code></pre>
  
  <p>A service function: </p>
  
  <pre><code>public function findOrCreatePerson ($data) 
  {
      $em = $this-&gt;em;
  
      $person = $em-&gt;getRepository('AppBundle:Person')-&gt;findOneBy([
          'first_name' =&gt; $data['first_name'],
          'last_name' =&gt; $data['last_name']
      ]);
  
      if(is_null($person)) {
          $person = new Person();
          $person-&gt;setFirstName($data['first_name']);
          $person-&gt;setLastName($data['last_name']);
          $em-&gt;persist($person);
      }
  
      return $person
  }
  </code></pre>
  
  <p>I tried to make it as simple as possible. </p>
  
  <p>As you can see, I would like to make only one DB transaction to get some performance improvements. </p>
  
  <p>Problem is, if I don't flush at the end of the <code>findOrCreatePerson()</code> method, the query to the <code>Person</code> repository won't find the first object and will create duplicates in the database. </p>
  
  <p><strong>My question is simple: How should I implement such a thing?</strong> </p>