title: Grails: how to generate a human-friendly for-sure-unique random number
body: <p>I have a domain class which will have many children.  Related to this other post of mine: <a href="https://stackoverflow.com/questions/9204723/grails-how-to-structure-transactions-when-i-want-to-continue-validating-even-af">Grails: how to structure transactions when I want to continue validating even after the transaction has already failed</a>  I want to create an instance of the parent class (MikeyJob), but NOT save it.  Then make a bunch of children, and only if the children validate, save the parent and all the children.</p>
  
  <p>This is all fine and good, but <code>MikeyJob</code> 's need a job number and this number must be unique.  This is confusing me because there will be lots of "maybe it will get saved" <code>MikeyJob</code>s floating around in different sessions.</p>
  
  <p>This is my thought:</p>
  
  <pre><code>import java.util.Random
  Class MikeyJob{
    BigInteger jobNumber
  
    def beforeInsert() = {
      //this is where I think I need help
      Random rand = new Random()
      BigInteger max = 99999999
      BigInteger randomInt = rand.nextInt(max)
      MikeyJob.withSession{
        while(randomInt&lt;9999999 || MikeyJob.findByJobNumber(randomInt)){
         randomInt = rand.nextInt(max)
        }
      }
      this.jobNumber = randomInt
    }
  
    static hasMany=[jobItems:JobItem]
    static constraints = {
      jobNumber(nullable:true)
    }
  }
  
  Class JobItem{
    String importantStuff
  }
  </code></pre>
  
  <p>So I have a service that basically goes like this:</p>
  
  <pre><code>Class JobMakerService{
    def makeAJob(def bigMessyList){
      def someNewJob = new MikeyJob()  /NOT SAVED
      def validItems = []
      def invalidItems = []
      bigMessyList.each{
        def jobItem = //pseudo code to get a job item out of messy list
        //also not saved
        if(jobItem.validate())validItems.add jobItem
        else invalidItems.add jobItem
  
  
      }
      if(invalidItems = []){
        someNewJob.save()
        validItems.each{
          it.save()
        }
      } else def errorHandling  = 1/0
  
  
    }
  }
  </code></pre>
  
  <p>This seems to be working, but is there a better way?</p>