4

How can I create named unique constraint for multiple columns?

I've three classes:

class Descriptor {
    // some columns
}

class Protein {
    // some columns
}

class DescriptorValue {
    // some columns
    static belongsTo = [protein: Protein, descriptor: Descriptor]
    static constraints = {
        protein(unique:['descriptor'])
    }
}

GORM creates an index with an auto generated name that is different for different environments. How can I specify its name?

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
Sergey Ponomarev
  • 2,947
  • 1
  • 33
  • 43

2 Answers2

1

Try to do it like:

static mapping = {
    protein unique:['descriptor'], index: 'protein_idx' //or whatever name you like
}

If you need to use multi-column indices, then you can specify for every property the same index name.

Tiago Farias
  • 3,397
  • 1
  • 27
  • 30
  • Is this for a specific version of grails? I'm currently stuck on grails 2.2.5, and using unique: ['descriptor'] doesn't work. (that syntax works in the constraints section, but not in the mapping section). The above code results in a unique constraint on protein with an index name of 'protein', and a 2nd non unique index named 'protein_idx' on the protein column. – burns Jun 29 '15 at 05:29
  • I think @stokito was asking if you could name the constraint. The above will name the constraint (in sql) something like 'protein_unique'. As far as I can tell you can't set the constraint name, which is a problem with unique constraints since, ironically, their names need to be unique. – pmc Aug 21 '18 at 04:31
0
String field1
String field2
Integer field3
SomeObject object

  static constraints = {
        object unique: ['field1','field2', 'field3']
    }