Thursday, May 8, 2008

Composite Key in Domain Class - round 2

Still tinkering with the composite key issues.

I changed my previous approach a bit, I now define my own getId and setId methods to essentially serialize and deserialize the the key fields strung together

Created a delimiter
static final String delimiter = '~@'

Defined (overriding default) accessors:
def getIdAsMap() {
["fieldOne": fieldOne, "fieldTwo": fieldTwo]
}

def getId() {
fieldOne + delimiter + fieldTwo
}

def setId(String inString) {
def fieldList = new ArrayList()
def items = inString.split(delimiter)
items.each { fieldList.add (it) }
this.setFieldOne (fieldList[0])
this.setFieldTwo (fieldList[1])
getIdAsMap()
}

Its a little clunky but when you can pass around the map, use getIdAsMap(), in other cases the String is available with myclass.id


Inserting new rows requires a little tweak, by default with version: false set, GORM will try to perform a sql update on new records. To fix this, add insert:true to your save method

myClass.save(insert: true)

No comments: