title: Grails 2.3 and Hibernate4: unique constraint name collision
body: <p><strong>UPDATE:</strong> This may turn out to be a Grails bug: <a href="https://jira.grails.org/browse/GRAILS-11600" rel="nofollow">https://jira.grails.org/browse/GRAILS-11600</a></p>
  
  <hr>
  
  <p>Ever since upgrading my Grails app to Hibernate4 I am getting errors related to creating many of my unique constraints on startup, using both H2 and Postgres. For example:</p>
  
  <pre><code>ERROR hbm2ddl.SchemaExport  - HHH000389: Unsuccessful: alter table bravo add constraint unique_name  unique (bravo_prop, name)
  ERROR hbm2ddl.SchemaExport  - ERROR: relation "unique_name" already exists
  </code></pre>
  
  <p>I looked into the problem by creating a new simple Grails app. I've discovered that when using Hibernate4 the name of the constraint that gets created in the database is not "globally unique". Let me explain.</p>
  
  <p>If I have a property called "foo" with a unique constraint then the constraint's name in the database may end up being called "unique_foo" with Hibernate4 whereas with Hibernate3 it's called more like "[tablename]_foo_key".</p>
  
  <p>When does this become a problem? <strong>It's an issue when I have multiple entities that have unique constraints on properties of the same name.</strong> For example: Entity1 has prop "foo" with a unique constraint, and so does Entity2. SchemaExport will fail when creating the unique constraint for Entity2.</p>
  
  <p>Here's some code to illustrate:</p>
  
  <pre><code>class Alpha {
      String name
      String alphaProp
      String alphaProp2
  
      static constraints = {
          // With Hibernate4.3.5.1|4 and either Grails 2.3.8 or 2.3.11, produces static constraint name: 'unique_name' =&gt; BAD
          // With Hibernate3, produces a unique constraint name: 'alpha_alpha_prop_name_key' (notice the entity namespace prefix) =&gt; GOOD
          name unique: 'alphaProp'
  
          // With Hibernate4.3.5.4 and Grails 2.3.11, produces static constraint name: 'unique_name' =&gt; BAD
          // With Hibernate3 and Grails 2.3.11 produces unique name: 'alpha_alpha_prop2_alpha_prop_name_key' =&gt; GOOD
  //        name unique: ['alphaProp', 'alphaProp2']
  
          // With Hibernate4.3.5.4 and Grails 2.3.11, produces random constraint name such as: 'uk_5h01nufunln3bv2bgxtnr9sxw' =&gt; GOOD
          // With Hibernate3 and Grails 2.3.11 produces unique name: 'alpha_name_key' =&gt; GOOD
  //        name unique: true
      }
  }
  
  
  class Bravo {
      String name
      String bravoProp
  
      static constraints = {
          // This constraint creation will fail if a constraint by this name was already created by Alpha
          name unique: 'bravoProp'
      }
  }
  </code></pre>
  
  <p>Help? :)</p>