The Neo4jTemplate offers the convenient API of Spring templates for the Neo4j graph
database.
For direct retrieval of nodes and relationships, the getReferenceNode(),
getNode() and getRelationship() methods can be used.
There are methods (createNode() and createRelationship()) for creating nodes and
relationships that automatically set provided properties and optionally index certain fields.
Example 24.1. Neo4j template
import static org.springframework.data.graph.core.Property._; Neo4jOperations neo = new Neo4jTemplate(graphDatabaseService); Node michael = neo.createNode(_("name","Michael")); Node mark = neo.createNode(_("name","Mark")); Node thomas = neo.createNode(_("name","Thomas")); neo.createRelationship(mark,thomas, WORKS_WITH, _("project","spring-data")); neo.index("devs",thomas, "name","Thomas"); assert "Mark".equals(neo.query("devs","name","Mark",new NodeNamePathMapper()));
Adding nodes and relationships to an index is done with the index() method.
The query() methods either take a field/value combination to look for exact matches in the
index, or a Lucene query object or string to handle more complex queries. All query()
methods provide Path results to a PathMapper.
The traversal methods are at the core of graph operations. As such, they are fully supported in the
Neo4jTemplate. The traverseNext() method traverses to the direct neighbors
of the start node, filtering the relationships according to the parameters.
The traverse() method covers the full traversal operation that takes a
TraversalDescription (typically built with the Traversal.description()
DSL) and runs it from the start node. Each path that is returned by the traversal is passed to the
PathMapper to be converted into the desired type.
For the querying operations Neo4jTemplate unifies the result with the Path abstraction that
comes from Neo4j. Much like a result set, a path contains a chain of nodes() connected by
relationships(), starting at a startNode() and ending at a
endNode(). The lastRelationship() is also available separately. The
Path abstraction also wraps results that contain just nodes or relationships.
Using implementations of PathMapper<T> and PathMapper.WithoutResult
(comparable with RowMapper and RowCallbackHandler), the paths can be converted
to arbitrary Java objects.
With EntityPath and EntityMapper there is also support for using
node entities within the Path and PathMapper constructs.
The Neo4jTemplate provides configurable implicit transactions for all its methods. By
default it creates a transaction for each call (which is a no-op if there is already a transaction
running). If you call the constructor with the useExplicitTransactions parameter set to
true, it won't create any transactions so you have to provide them using @Transactional
or the TransactionTemplate.