1

I have an ObjectContext stored in the session. Now I have multiple ajax requests for the same session, all modifying the data of ObjectContext. How do I go about ensuring these requests will be thread safe?

The following documentation suggests that I use context nesting. Can someone give me a concrete example of how this works? Or even an explanation of how nesting context will allow thread-safe requests. Or even a link to some documentation of best practices in these cases. Thanks!

https://cayenne.apache.org/docs/3.1/cayenne-guide/persistent-objects-objectcontext.html

Nesting is useful to create isolated object editing areas (child contexts) that need to all be committed to an intermediate in-memory store (parent context), or rolled back without affecting changes already recorded in the parent. Think cascading GUI dialogs, or parallel AJAX requests coming to the same session.

Edit: I found the following paragraph on the documentation which helped me.

Contexts that are only used to fetch objects from the database and whose objects are never modified by the application can be shared between multiple users (and multiple threads). Contexts that store modified objects should be accessed only by a single user (e.g. a web application user might reuse a context instance between multiple web requests in the same HttpSession, thus carrying uncommitted changes to objects from request to request, until he decides to commit or rollback them). Even for a single user it might make sense to use mutliple ObjectContexts (e.g. request-scoped contexts to allow concurrent requests from the browser that change and commit objects independently)

4

1 回答 1

2

如果您不在请求之间在服务器上保留未提交的更改,甚至还有更简单的解决方案。不要使用会话范围的 ObjectContext。而是使用每个请求甚至每个方法的上下文。当给定请求引入的所有更改都在单个方法调用中隔离时,每个方法在典型情况下起作用。然后,您将在方法条目上创建上下文,加载对象(使用查询或通过“localObject”从另一个上下文传输),执行更改,提交。之后,上下文被丢弃。例如:

public void myActionMethod() {
     ObjectContext peer = serverRuntime.newContext();
     ... do work with objects in 'peer'
     peer.commitChanges();
}

现在,如果您确实保留未提交的更改,您仍然可以使用每个方法的上下文,但嵌套的 . 所以上面的例子变成了这样:

public void myActionMethod() {
     ObjectContext nested = serverRuntime.newContext(sessionContext);
     ... do work with objects in 'nested'
     nested.commitChangesToParent();
}
于 2015-04-10T07:00:55.387 回答