When should I call javax.jdo.Query.close(Object) and Persistence Manager in JDO?

33 views Asked by At

I have an old project where I used JDO to fetch the data from Datastore. I have the following code

    public List<User> findAll() {

        LOGGER.info("Getting users list");
        Query query = null;
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            query = pm.newQuery(User.class);
            List<User> user = (List<User>) query.execute();
            return user;
        } catch (Exception e) {
            LOGGER.error("Error while getting user list", e);
            return Collections.emptyList();
        } finally {
            if(query != null) query.closeAll();
            pm.close();
        }
    }

I am calling the above method from my service and when I try to process the result, I am getting an error as

javax.jdo.JDOUserException: Query result has been closed

I tried to copy the result set to new list and return it but it also didn't work.

List<User> user = (List<User>) query.execute();
return new ArrayList<>(user);

How can I solve the issue? Shouldn't we have to close the query and pm ?

1

There are 1 answers

3
skillup On

You can test this code :

  public List<User> findAll() {
    LOGGER.info("Getting users list");
    PersistenceManager pm = PMF.get().getPersistenceManager();        
    Query query  = pm.newQuery(User.class);
    try {
        return (List<User>) query.execute();
    } catch (Exception e) {
        LOGGER.error("Error while getting user list", e);
        return Collections.emptyList();
    } finally {
        query.closeAll();
    }
  }