title: Spring Boot locking code to get an unique id
body: <p>I wrote a controller that must return an unique String. The requirement is that two calling of this controller never return the same String, even after years and even if the code will scale to more VMs.</p>
  
  <p>My question is if the following code is correct to achieve to declared purpose, or if you have any hint.</p>
  
  <p>Controller:</p>
  
  <pre><code>@RestController
  public class UtilityController {
  
      @Autowired
      UtilityServices utilityServices;
  
      @GetMapping("/uniqueIdentifier")
      @ResponseBody
      public String uniqueIdentifier() {
          return utilityServices.getUniqueIdentifier();
      }
  </code></pre>
  
  <p>Service:</p>
  
  <pre><code>@Service
  public class UtilityServices {
  
      @Autowired
      private UniqueIdRepository uniqueIdRepository;
  
      @Transactional
      public String getUniqueIdentifier() {
         String uniqueId = RandomString.getSecureRandomString();
         while (uniqueIdRepository.existsById(uniqueId)) {
             uniqueId = RandomString.getSecureRandomString();
         }
         uniqueIdRepository.save(new UniqueId(uniqueId));
         return uniqueId;
      }
  }
  </code></pre>
  
  <p>Entity:</p>
  
  <pre><code>@Entity
  @AllArgsConstructor
  @NoArgsConstructor
  @Getter
  @Setter
  @EqualsAndHashCode
  @ToString
  public class UniqueId implements Serializable {
  
      @Id
      private String uniqueId;   
  
  }
  </code></pre>
  
  <p>Repository:</p>
  
  <pre><code>public interface UniqueIdRepository extends CrudRepository&lt;UniqueId, String&gt; {
  
  }
  </code></pre>
  
  <p>That's all. I omit the code the <code>RandomString</code> class because it's not relevant in this context: I wrote a code based on <code>SecureRandom</code>, it is very likely that each time it returns a different String, but I have no guarantees about it. Let's assume that sooner or later my <code>RandomString.getSecureRandomString()</code> method can return the same String.</p>
  
  <p>I'm not sure if the <code>@Transactional</code> annotation guarantees that the <code>getUniqueIdentifier()</code> method never throws an error.</p>