Question

For the record, I am using Neo4j 2.0.0-M02.

I currently have a method which can search nodes with the label "User" on their user id which is stored in the graph as a node property "id". This all happens in a transaction, as that automatically closes the ResourceIterator.

Now, I want to create a relationship between two users. All I have is their user id. Now, I would obviously like to reuse the method which searches users by their id. And there are three ways I can think of.

The first one is the obvious one. Retrieve the two nodes with the already existing method. Than call the method that creates the relationship between them. Obviously this happens in a transaction as well so this would require three transactions. Not that efficient.

The second one is just to reuse the code (not the method) in the new method that creates the relationship. This way, I can do it all in one transaction, but I am duplicating code which isn't really good practice for developers.

A third one is to call the existing method twice inside the transaction of the new method that creates the relationship. That way my code is still reusable, but I am not sure how nested transactions work in Neo4J. Would the transactions from the existing method be ignored because there already is an existing transaction? That would solve my problem.

If not, I have to rethink where I manage my transactions. I know it's normally better to manage them in the services than in the DAO's but I'd like to keep Neo4j stuff out of my service classes.

Was it helpful?

Solution

The third option is how it will work, since there's not really nested transactions in neo4j but instead very shallow transactions where there's an existing outer transaction, so practically no overhead.

Transaction tx = db.beginTx();
try
{
    otherMethod( db );
    tx.success();
}
finally
{
    tx.finish();
}

private void otherMethod( GraphDatabaseService db )
{
    Transaction tx = db.beginTx();
    try
    {
        // do some other stuff...
        tx.success();
    }
    finally
    {
        tx.finish();
    }
}

In the above example calling otherMethod() will work with or without an existing transaction. If a transaction exists the operations it performs will take place in it, but if there's no existing transaction one will be created. So both will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top