Gideon
Gideon

Reputation: 1507

Grails domain not persisting even with flush: true parameters

I am having difficulty in inserting a new record using Grails domain class:

Integer lastId = AdjustmentCode.createCriteria().get {
    projections { max "id" }
} as Integer

def adjustmentCode = new AdjustmentCode()
adjustmentCode.setId(String.valueOf(lastId + 1))
adjustmentCode.setDescription(description)
adjustmentCode.setType(type)
adjustmentCode.setStatus(status)

println "before saving"
def status_e = adjustmentCode.save(flush: true, failOnError: true)

println "status_e: $status_e"
if(!status_e) { println adjustmentCode.errors.allErrors() }

println "after saving"

The console displays:

before saving
status_e: AdjustmentCode : 14
after saving

There is nothing wrong with adjustmentCode.save(flash: true, failOnError: true), I had provided all the required (and all the nullable ones too). And it doesn't returns any error messages, nor reaches the println adjustmentCode.errors.allErrors() line. What seems to be the error why it does not save?


EDIT 1: Because of zoran119 advise to enable the sql logging, I've found out that the .save() function generates an update statement, not an insert one. Now I explicitly tell the .save () function that it should create an insert sql statement by using the insert params:

def status_e = adjustmentCode.save(flush: true, failOnError: true, insert: true)
                                                                   ^^^^^^^^^^^^

But still it performs an update query! What should I do to make it create an insert statement?

Upvotes: 0

Views: 384

Answers (1)

Igor
Igor

Reputation: 33963

The problem may be that you are manually setting the id -- this is a little dangerous, as it means you will perform an update rather than an insert if the id already exists (assuming unique/primary keys). Try letting the database handle id generation and you should be OK.

Upvotes: 1

Related Questions