Welcome!

Java Authors: James Carlini, Dana Gardner, Elizabeth White, Gary Kaiser, Noel Wurst

Related Topics: Java, SOA & WOA

Java: Book Excerpt

Book Excerpt | Good Relationships: The Spring Data Neo4j Guide Book

Part 1: Tutorial - the creation of cineasts.net, a complete web application

The Spring Data Neo4j Project
This project is part of the Spring Data project, which brings the convenient programming model of the Spring Framework to modern NOSQL databases. Spring Data Neo4j, as the name alludes to, aims to provide support for the graph database Neo4j.

Tutorial
The first part of the book provides a tutorial that walks through the creation of a complete web application called cineasts.net, built with Spring Data Neo4j. Cineasts are people who love movies, and the site is a gathering place for moviegoers. For cineasts.net we decided to add a social aspect to the rating of movies, allowing friends to share their scores and get recommendations for new friends and movies.

The tutorial takes the reader through the steps necessary to create the application. It provides the configuration and code examples that are needed to understand what's happening in Spring Data Neo4j. The complete source code for the app is available on Github.

Introducing Our Project
Once upon a time we wanted to build a social movie database. At first there was only the name: Cineasts, the movie enthusiasts who have a burning passion for movies. So we went ahead and bought the domain cineasts.net, and so we were off to a good start.

We had some ideas about the domain model too. There would obviously be actors playing roles in movies. We also needed someone to rate the movies - enter the cineast. And cineasts, being the social people they are, they wanted to make friends with other fellow cineasts. Imagine instantly finding someone to watch a movie with, or share movie preferences with. Even better, finding new friends and movies based on what you and your friends like.

When we looked for possible sources of data, IMDB was our first stop. But they're a bit expensive for our taste, charging $15k USD for data access. Fortunately, we found themoviedb.org which provides user-generated data for free. They also have liberal terms and conditions, and a nice API for retrieving the data.

We had many more ideas, but we wanted to get something out there quickly. Here is how we envisioned the final website:

The Spring Stack
Being Spring developers, we naturally chose components from the Spring stack to do all the heavy lifting. After all, we have the concept etched out, so we're already halfway there.

What database would fit both the complex network of cineasts, movies, actors, roles, ratings, and friends, while also being able to support the recommendation algorithms that we had in mind? We had no idea.

But hold your horses, there is this new Spring Data project, started in 2010, that brings the convenience of the Spring programming model to NOSQL databases. That should be in line with what we already know, providing us with a quick start. We had a look at the list of projects supporting the different NOSQL databases out there. Only one of them mentioned the kind of social network we were thinking of - Spring Data Neo4j for the Neo4j graph database. Neo4j's slogan of "value in relationships" plus "Enterprise NOSQL" and the accompanying docs looked like what we needed. We decided to give it a try.

Required Setup
To set up the project we created a public Github account and began setting up the infrastructure for a Spring web project using Maven as the build system. We added the dependencies for the Spring Framework libraries, added the web.xml for the DispatcherServlet, and the applicationContext.xml in the webapp directory.

Example 2.1. Project pom.xml
<properties>
<spring.version>3.0.7.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<!-- abbreviated for all the dependencies -->
<artifactId>spring-(core,context,aop,aspects,tx,webmvc)</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

Example 2.2. Project web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

With this setup in place we were ready for the first spike: creating a simple MovieController showing a static view. See the Spring Framework documentation for information on doing this.

Example 2.3. applicationContext.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:spring-configured/>
<context:component-scan base-package="org.neo4j.cineasts">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<tx:annotation-driven mode="proxy"/>
</beans>

Example 2.4. dispatcherServlet-servlet.xml
<mvc:annotation-driven/>
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<context:component-scan base-package="org.neo4j.cineasts.controller"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>

We spun up Tomcat in STS with the App and it worked fine. For completeness we also added Jetty to the maven-config and tested it by invoking mvn jetty:run to see if there were any obvious issues with the config. It all seemed to work just fine.

Setting the Stage
We wanted to outline the domain model before diving into library details. We also looked at the data model of the themoviedb.org data to confirm that it matched our expectations. In Java code this looks pretty straightforward: The domain model:

Example 3.1. Domain model
class
Movie {
String id;
String title;
int
year;
Set<Role> cast;
}
class
Actor {
String id;
String name;
Set<Movie> filmography;
Role playedIn(Movie movie, String role) { ... }
}
class
Role {
Movie movie;
Actor actor;
String role;
}
class
User {
String login;
String name;
String password;
Set<Rating> ratings;
Set<User> friends;
Rating rate(Movie movie, int stars, String comment) { ... }
void
befriend(User user) { ... }
}
class
Rating {
User user;
Movie movie;
int
stars;
String comment;
}

Then we wrote some simple tests to show that the basic design of the domain is good enough so far. Just creating a movie, populating it with actors, and allowing users to rate it.

Learning Neo4j
Graphs Ahead

Now we needed to figure out how to store our chosen domain model in the chosen database. First we read up on graph databases, in particular our chosen one, Neo4j. The Neo4j data model consists of nodes and relationships, both of which can have key/value-style properties. What does that mean, exactly? Nodes are the graph database name for records, with property keys instead of column names.

That's normal enough. Relationships are the special part. In Neo4j, relationships are first-class citizens, meaning they are more than a simple foreign-key reference to another record; relationships carry information. So we can link together nodes into semantically rich networks. This really appealed to us. Then we found that we were also able to index nodes and relationships by {key, value} pairs. We also found that we could traverse relationships both imperatively using the core API and declaratively using a query-like Traversal Description. Besides those programmatic traversals there was the powerful graph query language called Cypher and an interesting looking DSL named Gremlin. So there was lots of ways of working with the graph.

We also learned that Neo4j is fully transactional and therefore upholds ACID guarantees for our data. Durability is actually a good thing and we didn't have to scale to trillions of users and movies yet.

This is unusual for NOSQL databases, but easier for us to get our head around than non-transactional eventual consistency. It also made us feel safe, though it also meant that we had to manage transactions. Something to keep in mind later.

We started out by doing some prototyping with the Neo4j core API to get a feeling for how it works. And also to see what the domain might look like when it's saved in the graph database. After adding the Maven dependency for Neo4j, we were ready to go.

Example 4.1. Neo4j Maven dependency
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>1.6.M02</version>
</dependency>
Learning Neo4j

Example 4.2. Neo4j core API (transaction code omitted)
enum RelationshipTypes implements RelationshipType { ACTS_IN };
GraphDatabaseService gds = new EmbeddedGraphDatabase("/path/to/store");
Node forrest=gds.createNode();
forrest.setProperty("title","Forrest Gump");
forrest.setProperty("year",1994);
gds.index().forNodes("movies").add(forrest,"id",1);
Node tom=gds.createNode();
tom.setProperty("name","Tom Hanks");
Relationship role=tom.createRelationshipTo(forrest,ACTS_IN);
role.setProperty("role","Forrest");
Node movie=gds.index().forNodes("movies").get("id",1).getSingle();
assertEquals("Forrest Gump", movie.getProperty("title"));
for
(Relationship role : movie.getRelationships(ACTS_IN,INCOMING)) {
Node actor=role.getOtherNode(movie);
assertEquals("Tom Hanks", actor.getProperty("name"));
assertEquals("Forrest", role.getProperty("role"));
}

Spring Data Neo4j
Conjuring magic

So far it had all been pure Spring Framework and Neo4j. However, using the Neo4j code in our domain classes polluted them with graph database details. For this application, we wanted to keep the domain classes clean. Spring Data Neo4j promised to do the heavy lifting for us, so we continued investigating it.

Spring Data Neo4j comes with two mapping modes. The more powerful one depends heavily on AspectJ, so we ignored it for the time being. The simple direct POJO-mapping copies the data out of the graph and into our entities. Good enough for a web-application like ours.

The first step was to configure Maven:

Example 5.1. Spring Data Neo4j Maven configuration
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>

The Spring context configuration was even easier, thanks to a provided namespace:

Example 5.2. Spring Data Neo4j context configuration
<beans xmlns="http://www.springframework.org/schema/beans" ...
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xsi:schemaLocation="... http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd">

...
<neo4j:config storeDirectory="data/graph.db"/>

...
</beans>

Annotating the Domain
Decorations

Looking at the Spring Data Neo4j documentation, we found a simple Hello World example and tried to understand it. We also spotted a compact reference card that 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. The only additional field we had to provide for all entities was an id-field to store the node- and relationship-ids.

Example 6.1. Movie class with annotation
@NodeEntity
class
Movie {
@GraphId Long nodeId;
String id;
String title;
int
year;
Set<Role> cast;
}

It was time to put our entities to the 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. The same goes for persisting entities, both Neo4jTemplate or the Repository could be used. We decided to keep things simple for now. Here's what our test ended up looking like:

Example 6.2. First test case
@Autowired Neo4jTemplate template;
@Test @Transactional public void persistedMovieShouldBeRetrievableFromGraphDb() {
Movie forrestGump = template.save(new Movie("Forrest Gump", 1994));
Movie retrievedMovie = template.findOne(forrestGump.getNodeId(), Movie.class);
assertEqual("retrieved movie matches persisted one", forrestGump, retrievedMovie);
assertEqual("retrieved movie title matches", "Forrest Gump", retrievedMovie.getTitle());
}

As Neo4j is transactional, we have to provide the transactional boundaries for mutating operations.

Indexing
Do I Know You?

There is an @Indexed annotation for fields. We wanted to try this out, and use it to guide the next test. We added @Indexed to the id field of the Movie class. This field is intended to represent the external ID that will be used in URIs and will be stable across database imports and updates. This time we went with a simple GraphRepository to retrieve the indexed movie.

Example 7.1. Exact Indexing for Movie id
@NodeEntity class Movie {
@Indexed String id;
String title;
int
year;
}
@Autowired Neo4jTemplate template;
@Test @Transactional
public void
persistedMovieShouldBeRetrievableFromGraphDb() {
int
id = 1;
Movie forrestGump = template.save(new Movie(id, "Forrest Gump", 1994));
GraphRepository<Movie> movieRepository =
template.repositoryFor(Movie.class);
Movie retrievedMovie = movieRepository.findByPropertyValue("id", id);
assertEqual("retrieved movie matches persisted one", forrestGump, retrievedMovie);
assertEqual("retrieved movie title matches", "Forrest Gump", retrievedMovie.getTitle());
}

Repositories
Serving a Good Cause

We wanted to add repositories with domain-specific operations. Interestingly there was support for a very advanced repository infrastructure. Just declare an entity-specific repository interface and get all commonly used methods for free without implementing any of the boilerplate code. We started by creating a movie-related repository, simply by creating an empty interface.

Example 8.1. Movie repository
package
org.neo4j.cineasts.repository;
public interface
MovieRepository extends GraphRepository<Movie> {}

Then we enabled repository support in the Spring context configuration by simply adding:

Example 8.2. Repository context configuration
<neo4j:repositories base-package="org.neo4j.cineasts.repository"/>

Besides the existing repository operations (like CRUD, and many standard queries) it was possible to declare custom methods, which we explored later. Those methods' names could be more domain-centric and expressive than the generic operations. For simple use-cases like finding by ids this is good enough. We first let Spring autowire our MovieController with the MovieRepository. That way we could perform simple persistence operations.

Example 8.3. Usage of a repository
@Autowired MovieRepository repo;

...
Movie movie = repo.findByPropertyValue("id",movieId);

We went on exploring the repository infrastructure. A very cool feature was something that we so far only heard about from Grails developers. Deriving queries from method names. Impressive! We had a more explicit method for the id lookup.

Example 8.4. Derived movie-repository query method
public interface
MovieRepository extends GraphRepository<Movie> {
Movie getMovieById(String id);
}

In our wildest dreams we imagined the method names we would come up with, and what kinds of queries those could generate. But some more complex queries would be cumbersome to read and write. In those cases it is better to just annotate the finder method. We did this much later, and just wanted to give you a peek into the future. There is much more, you can do with repositories; it is worthwhile to explore.

Example 8.5. Annotated movie-repository query method
public interface
MovieRepository extends GraphRepository<Movie> {
@Query("start user=node:User({0}) match user-[r:RATED]->movie return movie order by r.stars desc limit Iterable<Movie> getTopRatedMovies(User uer);
}

•   •   •

Republished from the Good Relationships: The Spring Data Neo4j Guide Book.

More Stories By Mike Hunger

Mike Hunger has been passionate about software development for a long time. He is particularly interested in the people who develop software, software craftsmanship, programming languages, and improving code. For the last two years he has been working with Neo Technology on the Neo4j graph database. As the project lead of Spring Data Neo4j he helped developing the idea to become a convenient and complete solution for object graph mapping. He is also taking care of Neo4j cloud hosting efforts.

As a developer he loves to work with many aspects of programming languages, learning new things every day, participating in exciting and ambitious open source projects and contributing to different programming related books. Michael is also an active editor and interviewer at InfoQ.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.