title: Do database transactions prevent race conditions?
body: <p>It's not entirely clear to me what transactions in database systems do. I know they can be used to rollback a list of updates completely (e.g. deduct money on one account and add it to another), but is that all they do? Specifically, can they be used to prevent race conditions? For example:</p>
  
  <pre><code>// Java/JPA example
  em.getTransaction().begin();
  User u = em.find(User.class, 123);
  u.credits += 10;
  em.persist(u); // Note added in 2016: this line is actually not needed
  em.getTransaction().commit();
  </code></pre>
  
  <p>(I know this could probably be written as a single update query, but that's not alway the case)</p>
  
  <p>Is this code protected against race conditions?</p>
  
  <p>I'm mostly interested in MySQL5 + InnoDB, but general answers are welcome too.</p>