I’m using JPA (not JDO) on Google App Engine and this is a typical example of my service method:
@Autowired
EntityManagerFactory entityManagerFactory;
public Collection<Message> getAll() {
EntityManager em = entityManagerFactory.createEntityManager();
Collection<Message> result = null;
try {
Query query = em.createQuery("SELECT e FROM Message e");
result = query.getResultList();
//The workaround
//if(result != null) result.size();
} finally {
em.close();
}
return result;
}
When I try to use the collection outside the method I get the “famous” error reporting that the object manager is closed. Calling the size() method is a workaround, but I dislike this kind of “dirty” solution. I wonder there isn’t any method to have this collection detached or lazy loading disabled.
I don’t know if it is “clean”, but a frequently recommended approach is to have a servlet filter that creates a thread-local EntityManager before your code runs and closes it at the very end.