Looking at the Spring Data Neo4j documentation, we found a simple
Hello World example
and tried to understand it. We also saw a compact reference card
which helped us a lot.
The entity classes were annotated with @NodeEntity
.
That was simple, so we added the annotation to our domain classes too. Entity classes representing
relationships were instead annotated with @RelationshipEntity
.
Property fields were taken care of automatically.
Example 6.1. Movie class with annotation
@NodeEntity class Movie { String id; String title; int year; Set<Role> cast; }
It was time to put our entities to a test. How could we now be assured that an attribute really was persisted to
the graph store? We wanted to load the entity and check the attribute.
Either we could have a Neo4jTemplate
injected and use its findOne(id,type)
method to load the entity. Or use a more versatile Repository
. We decided to keep things simple for now.
Looking at the documentation revealed that there are a bunch of methods introduced to the
entities by the aspects to support working with the entities.
That's not entirely obvious. We found two that would do the job:
entity.persist()
entity.getNodeId()
.
So here's what our test ended up looking like:
Example 6.2. First test case
@Autowired Neo4jTemplate template; @Test public void persistedMovieShouldBeRetrievableFromGraphDb() { Movie forrestGump = new Movie("Forrest Gump", 1994).persist(); Movie retrievedMovie = template.getById(forrestGump.getNodeId()); assertEqual("retrieved movie matches persisted one", forrestGump, retrievedMovie); assertEqual("retrieved movie title matches", "Forrest Gump", retrievedMovie.getTitle()); }
It worked! But hold on, what about transactions? After all, we had not declared the test to be
transactional. After some further reading we learned that calling persist()
outside
of a transaction automatically creates an implicit transaction. Very much like an EntityManager
would behave. We also learned that when performing more complex operations on the entities we'd
need external transactions, but not for this simple test.