Juri Adam
Juri Adam

Reputation: 569

When to use JDO DataNucleus Query.close()

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!

Upvotes: 0

Views: 284

Answers (1)

Neil Stockton
Neil Stockton

Reputation: 11531

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.

Upvotes: 3

Related Questions