tags:

views:

199

answers:

3

Hi,

How to catch duplicate key exceptions in Grails . when trying to save existing integer for a unique column constraint, the error is generating while saving/updating a record .

Also used
try{
object.save(flush:true)
}catch(org.springframework.
dao.DataIntegrityViolationException e){
println e.message
}catch(org.hibernate.exception.ConstraintViolationException ex){
println e.message
}catch(Exception e){
println e.message
}

But unable to catch this issue .

23:41:13,265 ERROR [JDBCExceptionReporter:101] Duplicate entry '1' for key 2
23:41:13,281 ERROR [AbstractFlushingEventListener:324] Could not synchronize database
state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:168) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)

Could you please share the solution to solve this .

A: 

You're trying to save a record with an id that already exists.

  • If id is auto-generated, don't set it manually
  • If id is not auto-generated, set it to something else, for example max(id) + 1
armandino
No, id is not auto generated and column is a unique key. Its a text field to enter and when user enters existing integer, it will fail to save. This works correctly, but in console i was getting the errors mentioned .
Srinath
A: 

surely no Exception should be thrown for constraint violation, but rather object.save() should return null? i.e.

if(object.save() == null) {
    // save failed
} else {
    // save succeeded
}
Alison
A: 

If you defined the uniqueness through a Grails constraint, you have to look for a ValidationException. This is thrown when object.validate() fails; Validation is done before any object.save().

try {
  object.save(failOnError: true)
}
catch(ValidationException ve) {
  // Do something ...
}

Bu remember: Any constraint violation, for any member variable can cause a ValidationException ... so you have to distiguish yourself.

Edit:

This applies, if you use the Grails 1.2 failOnError feature ...

air_blob
yeah, but i'm on grails-1.1.2
Srinath
Ok, now there are two possibilities: either try the common Grails validation procedure like if(obj.validate()) { obj.save() } else { obj.errors.each { // doh, there are errors ... } } (like Ali G mentioned) or a simpler and cleaner 'grails upgrade' ;)
air_blob