Redefine domain class mapping at runtime

旧街凉风 提交于 2019-12-13 07:39:41

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/13458286/redefine-domain-class-mapping-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!