register
other register

Tuesday, September 15, 2009

The unique constraint in Grails works fine out of the box when the field is not a primary key. But it cause exceptions if the field is a manually assigned primary key.
Also refer to Grails doc for unique constraint.

class Test
String id

static mapping = {
table 'test'
id generator:'assigned', column:'id'
}
static constraints = {
id(blank: false, unique: true)
}


Exception will be thrown when saving it with a duplicate id.



The solution is as below:

class TestController {
def save = {
def testInstance = new Test(params)
try {
if(!testInstance.hasErrors() && testInstance.save()) {
flash.message = "Test ${testInstance.id} created"
redirect(action:show,id:courseInstance.id)
}
else {
render(view:'create',model:[testInstance:testInstance])
}
}
catch (org.springframework.orm.hibernate3.HibernateSystemException e){
// Field in view to highlight using tag
testInstance.errors.rejectValue('id', 'test.id.notUnique')
render(view:'create',model:[testInstance:testInstance])
}
}
}

In the message.properties file, add one entry:

test.id.notUnique=The system has already had a id as you entered. Please provide a unique id.

No comments: