0

I was not able to find are clear documentation when to use the close() Method of the Query Object. In the following example the try with resources closes the PersistenceManager and the Query by calling Autocloseable.close(). Internally Query.close() call Query.closeAll(), which closes all returned results.

    Collection<Object> returnedEntities = new ArrayList<>();

    Transaction tx = null;
    try (PersistenceManager pm = DataStore.getInstance().getPM();
            Query< Object>query = pm.newQuery(Object.class);) {
        tx = pm.currentTransaction();

        tx.begin();
        query.setOrdering(<ordering>);
        query.setFilter(<some filters go here>);
        query.declareParameters(<parameterType>);
        returnedEntities = (Collection<Object>) query.execute(<parameterValue>);
        returnedEntities = pm.detachCopyAll(returnedEntities);
        tx.commit();

    } catch (Exception e) {
        //some error handling goes here...
    } finally {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    }

Is this the call of Query.close() necessary for the Query Object or is it enough to have the PersistenceManager closed and that then closes the rest? Some Documentation or Link is very much appreciated. Thanks!

Juri Adam
  • 569
  • 6
  • 21

1 Answers1

3

Query results do not outlast the PersistenceManager (PM) that created them, since the PM has the L1 cache etc (apart from when rows of the results are detached, so they continue to exist but the query result set will be closed). Close of a PM will close all resources it is responsible for (including all queries). So you just have to decide do I need to clear out my queries during the lifetime of the PM (i.e is your PM long lived?), and if so then use closeAll() or close() on the Query.

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
  • Perfect answer. Thank you! – Juri Adam Feb 08 '17 at 07:47
  • I had the same question. Many years ago when I started with DataNucleus I used to have long lived PMs but saw the light a long time ago and now all my DataNucleus/JDO PM are short lived and I use detach/attach in the right way. So the code that frees queries after each query is probably not necessary any more. – Volksman Feb 09 '22 at 22:43