title: JPA exception handling
body: <p>I'm running certain process that inserts new elements in DB from a for loop. I'm using JPA (Eclipselink), and sometimes there's a problem with the transation status. This is the case:</p>
  
  <ol>
  <li>One of the INSERTS doesn't work (Primary Key duplicated)</li>
  <li>After that, all the inserts will fail (Exception Description: Transaction is currently active).</li>
  </ol>
  
  <hr>
  
  <pre><code> for (Element l:e){
    try{
     //Should I add: if(!em.getTransaction().isActive())
     em.getTransaction().begin();
     em.createNativeQuery("INSERT INTO...").executeUpdate();
     em.getTransaction().commit();
     }
    catch(Exception ep)
    {
     //right now I don't do anything here
    }
   }
  </code></pre>
  
  <p>I get that what is happening is that, since the commit in 1) didn't work, the transaction didn't finish, so the next em.getTransaction().begin() will find an already active transaction.</p>
  
  <p>I have two ideas:</p>
  
  <p>A) Before em.getTransaction().begin(), check if the transcation is active, and only if it is not, call begin(); otherwise, create query and commit.</p>
  
  <p>B) Do something within the catch block. And here's my doubt... Should I call clear()? flush()? close()?</p>
  
  <p>Which one looks better?
  Thanks!</p>