Grails - 创建只读 api
我想将控制器中的某些操作限制为只读。 我有什么办法可以做到这一点吗? 我想要的是对于某些操作,事务在完成后不保存。
任何帮助表示赞赏。
我们正在谈论 1.3.7。
I would like to limit some of the actions in controllers to be read-only.
Is there any way I could do that?
What I want is the transaction not to save after it is finished, for certain actions.
Any help is appreciated.
We are talking about 1.3.7.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
“如何创建只读域”是邮件列表和其他地方时不时出现的内容。
简单的回答是:您无法 100% 防止写入。
实现某种只读的各种方法:
使用 .read() 方法获取对象,这确保您需要显式 .save() 来使项目持久化。
如果在sql上,您可以创建一个视图并创建一个域类映射到该视图,那么您将无法保存(并且尝试保存会抛出错误)。
使 beforeUpdate() 抛出异常,从而停止保存。
对静态映射 = {} 的更改,但我不太确定在那里做什么,我只记得邮件列表上提到的,如果您想找到,请通过谷歌搜索 grails-user 的 nabble 列表更改
如果你的东西相当静态,mysql 视图是一个不错的选择,如果你需要查询它们,beforeUpdate() 可能是不错的选择。
不过,您要求“只读操作”,您的意思是脚手架吗?以编程方式禁止在控制器操作中保存并不比不添加保存(或根本不修改对象)更难。
The 'how to make read only domains' is something that comes up now and then on the mailing lists and other places.
The quick answer is: You can't 100% secure against writes.
Various methods to achieve somewhat read only:
Use .read() method to get an object, that ensures that you need to explicitly .save() to make item persist.
If on sql, you can make a view and make a domain class map to this view, then you cant save (and trying to save will throw errors).
Make beforeUpdate() throw exception, thereby stopping the save.
Changes to static mapping = {}, but I am not quite sure what to do there, it has been mentioned on the mailing list is all I can remember, google through the nabble list for grails-user if you want to find out.
If your stuff is fairly static an mysql view is a good choice, if you need to query on them, the beforeUpdate() might be the good choice.
You ask for 'read only actions' though, do you mean scaffolded ones? Programmatically disallowing saving in a controller action is not harder than just.. not adding the save (or not modifying the object at all).
将逻辑放入grails服务的方法中
并将其标记为只读:
Put logic in method of grails service
and mark it as read-only:
您可以在域对象上使用
withTransaction
方法并将其设置为仅在那里回滚。http://grails.org/doc/latest/ref/Domain%20Classes /withTransaction.html
声明式事务管理是服务内置的,请参阅 Grails 参考手册,声明式事务。它不适用于控制器,但有一个插件: http://www.grails .org/plugin/transactional-controller
You can use
withTransaction
method on domain object and set it to rollback only there.http://grails.org/doc/latest/ref/Domain%20Classes/withTransaction.html
Declarative transaction management is built-in for services, see Grails reference manual, Declarative Transactions. It won't work for controllers, but there is a plugin for that: http://www.grails.org/plugin/transactional-controller
不确定这对您来说是否足够,但是有一个 read 方法是只读的,而不是 get http://grails.org/doc/latest/ref/Domain%20Classes/read.html
Not sure if that's enough for you, but there is a read method which is read-only as opposed to get http://grails.org/doc/latest/ref/Domain%20Classes/read.html