Last active
December 10, 2015 04:48
-
-
Save mikesname/4383741 to your computer and use it in GitHub Desktop.
Neo4j transaction handling, contrived example...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.neo4j.graphdb.Transaction; | |
import com.tinkerpop.blueprints.Vertex; | |
import com.tinkerpop.blueprints.impls.neo4j.Neo4jGraph; | |
public class Neo4jTest { | |
private final String[] testData = { | |
"foo", | |
"bar", | |
null, // Oops! Null property | |
"baz" | |
}; | |
private final Neo4jGraph graph; | |
public Neo4jTest() { | |
graph = new Neo4jGraph("test-graph" + (new java.util.Date()).getTime()); | |
} | |
public void createThing(String value) throws Exception { | |
Transaction tx = graph.getRawGraph().beginTx(); | |
try { | |
Vertex vertex = graph.addVertex(null); | |
vertex.setProperty("key", value); | |
tx.success(); | |
} catch (Exception e) { | |
tx.failure(); | |
throw e; | |
} finally { | |
tx.finish(); | |
} | |
} | |
public void createBatch() throws Exception { | |
Transaction tx = graph.getRawGraph().beginTx(); | |
try { | |
for (String t : testData) { | |
createThing(t); | |
} | |
tx.success(); | |
} catch (Exception e) { | |
tx.failure(); | |
throw e; | |
} finally { | |
tx.finish(); | |
} | |
} | |
public int countNodes() { | |
int count = 0; | |
for (Vertex _ : graph.getVertices()) count++; | |
return count; | |
} | |
public static void main(String[] args) { | |
Neo4jTest testRunner = new Neo4jTest(); | |
try { | |
testRunner.createBatch(); | |
} catch (Exception e) { | |
System.err.println("Caught exception: " + e.getMessage()); | |
} | |
System.out.println("Nodes in graph: " + testRunner.countNodes()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment