Grails: Is it possible to prevent a domain class i

2019-06-03 15:56发布

I want to create an (one) instance of a Domain class (which, as expected, has a GORM interface to my database) and only use it as a container to pass data around, like a Map object. I want to make absolutely sure that my instance is never going to get persisted in the database. I'm afraid that GORM, with all its cleverness, will somehow manage to save it in the database behind the scene even without an explicit call to save(). Is there a way to specify a "do not persist this" clause when instantiating my object? I know how to prevent persistence on a domain class, what I want is to prevent persistence on a particular instance of the class only.

The solution I have now is to create a class in groovy/src/ that carries the same properties and methods, and use it as my data container, and do type casts as required. It feels wrong, fails DRY, and hacky.

Of course you may also tell me that I should stop being so paranoid and that Grails is never going to persist an domain class instance without an explicit save.

标签: grails gorm
2条回答
虎瘦雄心在
2楼-- · 2019-06-03 16:44

Assume that, you already know how to prevent persistence(table creation) on a domain class. Furthermore, you also know that w/o explicit .save() object won't be persisted. So, what do you want actually? Is it like.. even if someone accidentally call obj.save(), it will never persist. Although that doesn't make any sense, but according to your query ,

Is there a way to specify a "do not persist this" clause when instantiating my object?

Yes, there is a way :

class MyFishyDomain {
 String pwd
 // properties 
 // constraints

   def beforeInsert() {
      if (!this.pwd.equals("drago")) return false
    }
    def beforeUpdate () {
      if (!this.pwd.equals("drago")) return false
    }

}

Now..

new MyFishyDomain(pwd:"drago").save()  // success
new MyFishyDomain(pwd:"rambo").save()  // fail

By the way, if you want to permanently disable Create+Update+Delete But at the same time want to issue query against domain then solution is:

static mapping = {
   cache usage: "read-only"
}
def beforeInsert() {
   return false
}
查看更多
聊天终结者
3楼-- · 2019-06-03 16:46

Grails will not save an instance of your domain class without an explicit call to save() on the instance. You can create an instance and pass it around, and it will not be persisted.

查看更多
登录 后发表回答