Prev |  | Next

## 33.5. Managing resources when using long running transactions

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 `ResourceIterator`s 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 don’t exhaust the iterator, we will close it explicitly using the `close()` method.

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

Copyright © 2014 Neo Technology

Prev | Up | Next
| Home |