evermean
evermean

Reputation: 1307

Redefine domain class mapping at runtime

I was wondering if there is a way in groovy to change the static mapping section of a grails class at runtime. As of now my domain class looks like this:

class Result {

    ObjectId id

    String url

    def Result(){

    }

    void addObjectProperty(String key, value){
        this[key]=value
    }

    //No constrains defined yet.
    static constraints = {
    }

    static mapWith="mongo"

    static mapping = {
        collection "results"
        database "test"
    }
}

Now lets just say I want to change the mapping section at runtime to:

static mapping = {
    collection "xyz"
    database "mydb"
}

Now when I call save() on an object it saves the result to mydb in the collection xyz. I bet there is a way in groovy to accomplish just that but since I'm new to groovy I'm having a hard time here ... it would be nice if someone could point me into the right direction.

Thanks a lot...

Upvotes: 0

Views: 1316

Answers (1)

Steve Goodman
Steve Goodman

Reputation: 1196

Note my comment above about the wisdom of doing this. That said, you can replace your mappings at runtime with Groovy's metaclassing functionality.

Result.metaClass.'static'.mapping = {
    collection "myCollection"
    database "myDatabase"
}

In Grails, the mapping block is a Groovy closure, so you're free to replace it with any other closure object whenever you'd like. This may have crazy unpredictable Hibernate side-effects or do nothing at all, as I do not know when the mapping closure is used to configure Hibernate in the Grails app lifecycle.

Upvotes: 2

Related Questions