如何在Google App Engine上的相同RPC请求中始终使用相同的PersistenceManager

时间:2010-01-07 15:18:22

标签: google-app-engine gwt jdo

有没有办法确保在同一RPC请求的上下文中执行的不同代码部分中使用相同的PersistenceManager实例?

必须从函数到函数手动处理持久性管理器实例是一件非常痛苦的事情:

例如:

private void updateItem(ItemModel listItem)
        throws UserNotLoggedInException {
   PersistenceManager pm = PMF.get().getPersistenceManager();
   if (isItemIsNew(pm, listItem)) { 
        workOnItem(pm, listItem);
   }
   workSomeMoreOnItem(pm, listItem);

}

1 个答案:

答案 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() {}
}

http://appengine-cookbook.appspot.com/recipe/persistencefilter/?id=ahJhcHBlbmdpbmUtY29va2Jvb2tyigELEgtSZWNpcGVJbmRleCI2YWhKaGNIQmxibWRwYm1VdFkyOXZhMkp2YjJ0eUVnc1NDRU5oZEdWbmIzSjVJZ1JLWVhaaERBDAsSBlJlY2lwZSI3YWhKaGNIQmxibWRwYm1VdFkyOXZhMkp2YjJ0eUVnc1NDRU5oZEdWbmIzSjVJZ1JLWVhaaERBMAw