Java IoT Authors: Elizabeth White, Liz McMillan, Yeshim Deniz, Zakia Bouachraoui, Pat Romanski

Related Topics: Java IoT, Microservices Expo

Java IoT: 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.

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
<!-- abbreviated for all the dependencies -->

Example 2.2. Project web.xml

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"
<context:component-scan base-package="org.neo4j.cineasts">
<context:exclude-filter type="annotation"
<tx:annotation-driven mode="proxy"/>

Example 2.4. dispatcherServlet-servlet.xml
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<context:component-scan base-package="org.neo4j.cineasts.controller"/>
<bean id="viewResolver"
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
Movie {
String id;
String title;
Set<Role> cast;
Actor {
String id;
String name;
Set<Movie> filmography;
Role playedIn(Movie movie, String role) { ... }
Role {
Movie movie;
Actor actor;
String role;
User {
String login;
String name;
String password;
Set<Rating> ratings;
Set<User> friends;
Rating rate(Movie movie, int stars, String comment) { ... }
befriend(User user) { ... }
Rating {
User user;
Movie movie;
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
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");
Node tom=gds.createNode();
tom.setProperty("name","Tom Hanks");
Relationship role=tom.createRelationshipTo(forrest,ACTS_IN);
Node movie=gds.index().forNodes("movies").get("id",1).getSingle();
assertEquals("Forrest Gump", movie.getProperty("title"));
(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

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" ...
xsi:schemaLocation="... http://www.springframework.org/schema/data/neo4j

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


Annotating the Domain

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
Movie {
@GraphId Long nodeId;
String id;
String title;
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.

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;
@Autowired Neo4jTemplate template;
@Test @Transactional
public void
persistedMovieShouldBeRetrievableFromGraphDb() {
id = 1;
Movie forrestGump = template.save(new Movie(id, "Forrest Gump", 1994));
GraphRepository<Movie> movieRepository =
Movie retrievedMovie = movieRepository.findByPropertyValue("id", id);
assertEqual("retrieved movie matches persisted one", forrestGump, retrievedMovie);
assertEqual("retrieved movie title matches", "Forrest Gump", retrievedMovie.getTitle());

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
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.

IoT & Smart Cities Stories
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
DXWorldEXPO LLC, the producer of the world's most influential technology conferences and trade shows has announced the 22nd International CloudEXPO | DXWorldEXPO "Early Bird Registration" is now open. Register for Full Conference "Gold Pass" ▸ Here (Expo Hall ▸ Here)
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of ...