Grails Gorm 部分保存
我在保存从通过 JSON 发送的客户端获得的对象时有一个非常基本的问题。
我有一个客户对象,该对象被传输到客户端,编辑客户后将其发送回 Grails 并需要保存在数据库中。为了提高性能,我不会通过网络发送完整的客户对象。
现在的问题是,如果我想存储客户对象,Grails 当然会验证客户对象的关系,但会失败。这没关系,因为我还没有发送关系。
我现在的问题是我现在该如何解决这个问题?我是否需要使用客户 ID 再次查询数据库并更新编辑的属性,还是有更优雅的方法?从数据库的角度来看,这看起来有点昂贵,因为我每次存储对象时都需要读取数据库。同样从代码角度来看,我需要检查设置了哪些属性并更新它们。
谢谢你!
I have a very basic question in saving objects which I get from a client sent via JSON.
I have a customer object which is transfered to the client, after editing the customer its send back to Grails and needs to be saved in the database. For performance I am not sending the complete customer object over the wire.
The problem is now if I want to store the customer object Grails validates of course the relationships of the customer object and fails. This is OK because I havent sent the relationsships.
My question is now how do I solve this problem now? Do I need to query the database again with the customer id and update the edited properties or is there a more elegant way? This looks a little bit expensive from database perspective as I need to read the database each time when storeing an object. As well from code perspective I need to check which properties are set and update them.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能使用 save() 进行部分更新,因为 grails 无法猜测您实际想要更新哪些字段:也许您真的想将字段值设置为 NULL,因此 Grails 不能忽略这些字段。所以我看到两个选项:
按照您所描述的那样进行操作:从数据库加载实例,设置值并再次保存。您已经提到,您不喜欢关心更新哪些字段,而只想获取 JSON 实例的所有属性。因此,假设您已解析的 JSON 实例名为
jsonInstance
并且您的客户数据库版本为customerInstance
,您可以执行以下操作:但是,请注意存在安全限制(如果攻击者将“id”属性或其他相关属性值注入其中,这些属性值将被覆盖)。
使用
executeUpdate
函数,参见:http://www.grails.org/doc/latest/ref /Domain%20Classes/executeUpdate.html
我想,如果你真的想节省性能,那就这样吧。但是,您有一些硬编码的 DML,这会降低可维护性和灵活性。
You cannot use
save()
for doing partial update, since grails cannot guess what fields you actually want to update: Maybe you REALLY want to set a field-value to NULL, so Grails cannot just ignore those fields. So I see two options:Do it like you have described: Load the instance from DB, set the values and save again. You have mentioned, that you do not like to care what fields are updated, and you just want to take all attributes of your JSON instance. So assuming your already parsed JSON-instance is called
jsonInstance
and your database version of the customer iscustomerInstance
, you can do:However, note that there are security limitations (if an attacker injects an 'id' attribute or other relevant attribute values into it, those will be just overwritten).
Use
executeUpdate
-function, see:http://www.grails.org/doc/latest/ref/Domain%20Classes/executeUpdate.html
I think, if you really want to save performance, then go like this. However you have some hardcoded DML, which will cost maintainability and flexibility.