title: grails: how to save a domain objects in bootstrap and avoid duplication by ignoring unique constraint errors?
body: <p>We have a lot of data created in the bootstrap.
  if you just do </p>
  
  <pre><code> def foo = new Foo(bar:"hello").save(failOnError:true)
  </code></pre>
  
  <p>and you start the app in a context such as test which has "dbCreate = "update"
  and bar has to be unique, then you will get an error as it tries to create 2 copies of the same piece of data.</p>
  
  <p>just calling save() without failOnError solves the problem partially, as now it creates the object in the DB if it was not there, and ignores it if it was already there (assuming there is at least one unique constraint to protect the object).</p>
  
  <p>However, this is not tenable, as it doesn't tell you if there was another error, such as this:</p>
  
  <pre><code>def foo = new Foo(barTypo:"hello").save()
  </code></pre>
  
  <p>and you end up without the piece of data in the DB and the app falls over in unexpected ways.</p>
  
  <p>The long winded solution is to do a find before every save:</p>
  
  <pre><code>def foo = Foo.findByBar("hello")?: new Foo(bar:"hello").save(failOnError:true)
  </code></pre>
  
  <p>However, I was trying to find a way less verbose.</p>
  
  <p>I tried this:</p>
  
  <pre><code>saveIgnoreDups(new foo(bar:"hello"))
  
  def saveIgnoreDups(ob) {
      try {
          ob.save(failOnError: true)
      } catch(org.springframework.dao.DataIntegrityViolationException e) {
          // fail silently - was already there.
      }
  }
  </code></pre>
  
  <p>But this doesn't work: the catch does not catch unique integrity constraint failures.</p>
  
  <p>I am sure there is an easy way to do this, but don't know where to find it.</p>
  
  <p>Any ideas?</p>