views:

245

answers:

0

I'm using JDO on AppEngine with Restlet + JAX-RS extensions. In my sub-resource locator class I load the entity in the constructor. Then for the various methods I used the data. If I close the PersistenceManager before returning from the Constructor, collections of one-to-many fields are not initialized and remain null.

I read about "detachable", but basically found I'd need to add the whole object graph to a fetch group in order to detach everything. I don't necessarily want to force the retrieval of all that data up front, unless it's needed.

So I've found simply not closing the persistence manager instance makes things work as expected, but I'm worried about what that means for the application. Is this going to cause problems?

In other apps I've build with Hibernate, I've had a ServletFilter on the application which would close any open session after the response was sent. I'm going to need this if I want to use something like JSP or Velocity templates to render HTML views for some resources.

Here's some sample code to refer to:

public class MenuResource {

    Menu menu;

    public MenuResource(long id) {
        PersistenceManager pm = PMF.get().getPersistenceManager();

        KeyFactory.Builder keyBuilder =
            new KeyFactory.Builder(Menu.class.getSimpleName(), id);
        Key key = keyBuilder.getKey();

        menu = pm.getObjectById(Menu.class, key);

       // calling pm.close() here breaks things (see below)

       // marking the object "detachable" and calling
       // detach() does not detach child collections by default
    }

    @GET
    @Produces("text/html")
    public String getAsHTML() {
       // displays some fields from the instance of menu

       // as well as iterate through a collection of child objects and
       // outputs fields from them as well.

       // if PersistenceManager is closed, the child collection is null
       // otherwise it works correctly.

       StringBuilder sb = new StringBuilder();
       sb.append("<html><body>");
       sb.append("<h1>").append(menu.getTitle()).append("</h1");

       sb.append("<ul>");       
       for (Item item : menu.getItems()) {
          sb.append("<li>").append(item.getText()).append("</li">);
       }
       sb.append("</ul>");
       sb.append("</body></html>");
       return sb.toString();
    }
}

Any advice in the proper patterns/approach here? I'd like not to have to resource to a ServletFilter with such a nice and clean framework as JAX-RS. Thanks!