title: Guarantee unique number generation with spring data and hibernate
body: <p>I'm developing a spring mvc webapp with spring data and hibernate.</p>
  
  <p>I've an entity composed by a boolean field and by an Integer field. </p>
  
  <p>At beginning the boolean field is false and Integer field is null.  </p>
  
  <p>When boolean field become true I need to assign to the Integer field a unique value equals to MAX(seq) +1</p>
  
  <p>To do it, I write my service method in this way:</p>
  
  <pre><code>@Override
  public synchronized Obj save(Obj entry) {
      if (entry.getBool() &amp;&amp; entry.getSeq() == null){
          Integer seq = objRepository.getLastSeq();
          if (seq == null){
              seq = 1;
          }
          entry.setSeq(seq);
      }
      return entry.save(entry);
  }
  </code></pre>
  
  <p>And in my Reposiroty: </p>
  
  <pre><code>@Query("select MAX(seq)+1 FROM Obj")
  Integer getLastSeq();
  </code></pre>
  
  <p>I put synchronized keyword to service method in order to be sure that only a thread at a time can get an unique MAX+1 number.. but I'm not sure if it works in all situation and if it is the right way.</p>
  
  <p>Can I be sure that it guarantee unicity of seq?</p>
  
  <p>Thank you
  Marco</p>