3.6. Managing resources when using long running transactions

This section describes how it is necessary to always open a transaction when accessing the database.

Inside a long running transaction it is good practice to ensure that any ResourceIterators obtained inside the transaction are closed as early as possible. This is either achieved by just exhausting the iterator or by explicitly calling its close method.

What follows is an example of how to work with a ResourceIterator. As we do not exhaust the iterator, we will close it explicitly using the close() method.

            Label label = Label.label( "User" );
            int idToFind = 45;
            String nameToFind = "user" + idToFind + "@neo4j.org";
            try ( Transaction tx = graphDb.beginTx();
                  ResourceIterator<Node> users = graphDb.findNodes( label, "username", nameToFind ) )
                Node firstUserNode;
                if ( users.hasNext() )
                    firstUserNode = users.next();