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() && {
flash.message = "Test ${} created"
else {
catch (org.springframework.orm.hibernate3.HibernateSystemException e){
// Field in view to highlight using tag
testInstance.errors.rejectValue('id', '')

In the file, add one entry: system has already had a id as you entered. Please provide a unique id.

No comments: