title: Concurrency with Hibernate in Spring
body: <p>I found a lot of posts regarding this topic, but all answers were just links to documentations with no example code, i.e., how to use concurrency in practice.</p>
  
  <p>My situation: I have an entity <code>House</code> with (for simplyfication) two attributes, <code>number</code> (the id) and <code>owner</code>. The database is initialized with 10 <code>Houses</code> with <code>number</code> 1-10 and <code>owner</code> always <code>null</code>.</p>
  
  <p>I want to assign a new owner to the house with currently no owner, and the smallest <code>number</code>. My code looks like this:</p>
  
  <pre><code>@Transactional
  void assignNewOwner(String newOwner) {
      //this is flagged as @Transactional too
      House tmp = houseDao.getHouseWithoutOwnerAndSmallestNumber();
  
      tmp.setOwner(newOwner);
  
      //this is flagged as @Transactional too
      houseDao.update(tmp);
  }
  </code></pre>
  
  <p>For my understanding, although the <code>@Transactional</code> is used, the same <code>House</code> could be assigned twice to different owners, if two requests fetch the same empty <code>House</code> as <code>tmp</code>. How do I ensure this can not happen?</p>
  
  <p>I know, including the update in the selection of the empty <code>House</code> would solve the issue, but in near future, I want to modify/work with the <code>tmp</code> object more. </p>