I decided to use Cypher to create a simple record. Here I tried to create a Movie instance
There are other ways to create nodes. This is just one way.
public Movie createMovie(String title, int released, String tagline) {
try (Transaction tx = graphDb.beginTx()) {
Map<String, Object> params = new HashMap<>();
params.put("mName", title);
params.put("releasedYear", released);
params.put("tagline", tagline);
Result result = graphDb.execute(
"CREATE (m :Movie { title:{mName},released:{releasedYear},tagline:{tagline} }) "
+ "RETURN m", params);The code executes a Cypher query that creates a node and returns the resultant Node.
if (result.hasNext()) {
while (result.hasNext()) {
Map<String, Object> row = result.next();
Node nodeProxy = (Node) row.get("m");
return extractMovie(nodeProxy);
}
}
}
returnnull;
}
publicstatic void main(String[] args) {The output of the created instance is :
MovieDAO movieDAO = new MovieDAO();
Movie newMovie = movieDAO.createMovie("Spectre", 2015, "");
System.out.println("New Movie added with id " + newMovie.getId());
}
New Movie added with id 171However if I look into Neo4j I do not see any new movies added. In fact if I ran the same code again, I would see a new movie created with the same id - this happens only if the id is available. This means that my transaction was not committed. Accordingly I changed the code:
Result result = graphDb.execute(When the transaction closes, the success call will make sure the commit occurs.In case of failure we have the close method rolling it back if the failure method had been invoked on the transaction.
"CREATE (m :Movie { title:{mName},released:{releasedYear},tagline:{tagline} }) " + "RETURN m", params);
tx.success();
public Movie createMovie(String title, int released, String tagline) {I verified the node presence by running a query on its id.
Movie newMovie = null;
finalString QUERY = "CREATE (m :Movie { title:{mName},released:{releasedYear},tagline:{tagline} }) RETURN m";
Map<String, Object> params = new HashMap<>();
params.put("mName", title);
params.put("releasedYear", released);
params.put("tagline", tagline);
try (Transaction tx = graphDb.beginTx()) {
try {
Result result = graphDb.execute(QUERY, params);
if (result.hasNext()) {
while (result.hasNext()) {
Map<String, Object> row = result.next();
Node nodeProxy = (Node) row.get("m");
newMovie = nodeProxy != null ? extractMovie(nodeProxy) : null;
}
}
if (newMovie != null) {
// Movie was not returned
tx.success();
}
} catch (Exception e) {
tx.failure();
}
}
return newMovie;
}
There are other ways to create nodes. This is just one way.