乐观锁定在一个RESTful应用程序中 [英] Optimistic locking in a RESTful application

查看:79
本文介绍了乐观锁定在一个RESTful应用程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在工作中,我们正在开发一个RESTful应用程序,其中数据层将由Hibernate处理。但我们不确定如何处理实体更新。



我们计划执行以下操作:

1)客户端通过id
来请求一个实体2)Hibernate加载实体,请求的字段(总是带有版本)被复制到一个转换为JSON并发送给客户端的DTO中>
3)客户端管理某些字段并将实体(带有版本号)发送回服务器。

4)服务器接收到转换为DTO的JSON。

5)相应的实体从Hibernate中加载,并且DTO的道具被复制到实体中。

=>实体总是被覆盖,即使客户端的版本号被设置。
这是否意味着我们必须通过自己而不是Hibernate来检查客户端版本号是否与已加载实例的版本号相同?



在具有会话的常规应用程序中,分离的实例保存在HttpSession中。无论何时客户端更新实体,都会从HttpSession中检索实例,并更新一些属性。每当Hibernate提交更新时,如果版本号为<>则抛出ObjectStaleException。当前的版本号。



这里的问题是我们没有任何Http会话,因为我们试图成为RESTful。



是否有一个通用的解决方案来处理RESTful应用程序中的乐观锁定,而不是自己检查版本号?

解决方案

<你的策略很好。只需将来自客户端的版本号复制到已加载的实体中(或者使用 merge(),这样做也是一样),当Hibernate刷新实体时,如果版本数字已经增加,你会有一个乐观的锁定异常。



你不需要自己检查任何东西。 Hibernate为你做检查。


At work, we're developing a RESTful application where the data layer will be handled by Hibernate. But we're not sure how to handle updates on entities.

We're planning to do the following:

1) client requests an entity by id
2) Hibernate loads the entity, the requested fields (always with the version) are copied to a DTO that is converted to JSON and sent to the client
3) Client manages some fields and sends the entity (with version number) back to the server.
4) Server receives the JSON that is converted to a DTO.
5) Corresponding entity is loaded from Hibernate and the DTO's props are copied to the entity.

=> The entity is always overwritten even if the version number of the client was set. Does this mean that we always have to check the version number of the client against the version number of the loaded instance by ourselves instead of Hibernate doing this?

In a regular application with sessions, the detached instance is saved in the HttpSession. Whenever the client updates the entity, the instance is retrieved from the HttpSession and some attributes are updated. Whenever Hibernate commits the update, a ObjectStaleException will be thrown if the version number is < the current version number.

The problem here is that we don't have any Http session because we're trying to be RESTful.

Is there a generic solution for handling optimistic locking in RESTful applications instead of checking version numbers by ourselves?

解决方案

Your strategy is good. Simply copy the version number coming from the client into the loaded entity (or use merge(), which will do the same), and when Hibernate flushes the entity, if the version number has been incremented, you'll have an optimistic lock exception.

You don't need to check anything by yourself. Hibernate does the check for you.

这篇关于乐观锁定在一个RESTful应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆