有没有办法确保在同一RPC请求的上下文中执行的不同代码部分中使用相同的PersistenceManager实例?
必须从函数到函数手动处理持久性管理器实例是一件非常痛苦的事情:
例如:
private void updateItem(ItemModel listItem)
throws UserNotLoggedInException {
PersistenceManager pm = PMF.get().getPersistenceManager();
if (isItemIsNew(pm, listItem)) {
workOnItem(pm, listItem);
}
workSomeMoreOnItem(pm, listItem);
}
答案 0 :(得分:2)
Google Cookbook提供以下答案:
使用过滤器,您可以使PersistenceManager可用并保证在请求结束时关闭它。如果您正在使用一个为您处理渲染的MVC框架(如Spring),那么这对于保持管理器打开足够长的时间以使View仍然能够获取尚未访问的持久对象也很有用。
public final class PersistenceFilter implements Filter {
private static final PersistenceManagerFactory persistenceManagerFactory
= JDOHelper.getPersistenceManagerFactory("transactions-optional");
private static PersistenceManagerFactory factory() {
return persistenceManagerFactory;
}
private static ThreadLocal currentManager = new ThreadLocal();
public static PersistenceManager getManager() {
if (currentManager.get() == null) {
currentManager.set(factory().getPersistenceManager());
}
return currentManager.get();
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
PersistenceManager manager = null;
try {
manager = getManager();
//Optional: allow all persistent objects implementing a custom interface
//to be notified of when they are saved and loaded.
manager.addInstanceLifecycleListener(new PersistHookListener(), PersistHooks.class);
chain.doFilter(req, res);
} finally {
if (manager != null) {
manager.flush();
manager.close();
}
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {}
@Override
public void destroy() {}
}