Syam
Syam

Reputation: 575

Set property method in grails could not change the instance globally

I have a domain class DbUserSchemaServer with a transient property unassign

class DbUserSchemaServer {
    static transients = ["unassign"]

    DbUser user
    String schema
    DbServer server
    BigInteger objects
    Date creationDate
    String schemaStatus //for dropping
    Boolean protect

    //Transients
    Boolean unassign

    static constraints = {
        user unique:false, nullable: false, blank:false
        schema unique:'server', nullable: false, blank:false
        server unique: false, nullable: false, blank:false
        objects blank:false, nullable:false
        creationDate blank:false, nullable:false
        schemaStatus nullable:true, blank: false
    }

    static mapping = {
        protect defaultValue: false
        unassign defaultValue: false
    }
}

In a service, I tried to change the value of protect property of a DbUserSchemaServer instance. The method as folows

public Boolean protectSchema(DbUserSchemaServer usrSchSrvInst) {
    println "protectSchema: "+usrSchSrvInst.schema
    if(!usrSchSrvInst.protect) { // If unprotected
        if(usrSchSrvInst.schemaStatus.equals("drop")) // If schema status is drop
            usrSchSrvInst.setSchemaStatus(null)
        usrSchSrvInst.setProtect(true)
        println "-->"+usrSchSrvInst.getProtect()
        return true
    }
    else {  // If already protected
        return true
    }

    return false
}

When I tried to change the status of a schema TEST_SCHEMA_1 by setProtect(true) call, it changes in the local view (prints true on std println), but doesn't change in the database entry. I tried to save the instance by instance.save() bu no change in the behavior.

I am using grails 2.4.4 now. Previously, I used version 2.2.4 and it worked as expected. I have this issue when I migrated the application to version 2.4.4. What could be the reason, and how could it be resolved.

Upvotes: 0

Views: 536

Answers (1)

John
John

Reputation: 11921

At what point in your service are you checking the state of the instance in the database? When is your instance created? Your method sets the protect variable but doesn't save the instance.

If you call save() then the instance isn't actually saved to the db, it's only saved to the DB when the session is flushed. Try using:

save(flush: true, failOnError: false)

Upvotes: 2

Related Questions