How to set default behaviour to Grails' Criteria?

匆匆过客 提交于 2020-01-23 19:22:27

问题


What I'd like to do is to set:

setReadOnly(true)

to every criteria query by default.

Is it possible to define default settings that would be applied to every single criteria query that is executed in the application?

P.S. I would possibly want to add the following as criteria defaults also but am unsure, whether they would have any additional effect to setReadOnly:

setCacheMode(CacheMode.IGNORE)
setFlushMode(FlushMode.MANUAL)

回答1:


Done some digging and found this for you:

http://www.javacodegeeks.com/2012/10/stuff-i-learned-from-grails-consulting.html

One limitation of the read method is that it only works for instances loaded individually by id. But there are other approaches that affect multiple instances. One is to make the entire session read-only:

1   session.defaultReadOnly = true

Now all loaded instances will default to read-only, for example instances from criteria queries and finders.

A convenient way to access the session is the withSession method on an arbitrary domain class:

1   SomeDomainClass.withSession { session ->
2      session.defaultReadOnly = true
3   }

It’s rare that an entire session will be read-only though. You can set the results of individual criteria query to be read-only with the setReadOnly method:

1   def c = Account.createCriteria()
2   def results = c {
3      between('balance', 500, 1000)
4      eq('branch', 'London')
5      maxResults(10)
6      setReadOnly true
7   }

One significant limitation of this technique is that attached collections are not affected by the read-only status of the owning instance (and there doesn’t seem to be a way to configure collection to ignore changes on a per-instance basis).

Read more about this in the Hibernate documentation



来源:https://stackoverflow.com/questions/21529503/how-to-set-default-behaviour-to-grails-criteria

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