Press "Enter" to skip to content

Week #9 – Connecting to Neo4j

The time has come to use the database in Commutee. You can do it pretty easily using Spring Data Neo4j, here’s how.

Spring offers so many tools, that it is hard to even know what it can do, and completely different thing is to know how to use these tools. Most of them are designed in such a way to be really easy to use. This is also true for Spring Data Neo4j, an abstraction layer over Neo4j database. It uses the same principles as the rest of the Spring Data projects. That means, that it has Repository classes generated from interface definitions that take care of all the boilerplate needed to talk to the database.

How to?

Adding neo4j to your project is really simple. First, you have to add the required dependencies, in maven case, something like that:

Next, you have to configure the connection to the database. you can do this by creating a spring configuration class and creating SessionFactory and neo4j Configuration beans.

As you see, there are only few thing that you have to provide.

  • database URL
  • credentials
  • you have to enable Neo4jRepositories and declare in which package they are located
  • you have to point SessionFactory to the package containing your entity classes

And that’s it. You have a working connection to the database.

Entities

Now that the connection is available, you can define your entities, or in the case of Neo4j, your nodes and relationships;

For nodes, you have to use NodeEntitiy annotation, in which you can specify a label for the node, like that:

Relationships are similar, but there are two ways to specify them. First, the simple way is just using an annotation Relationship on a field in your NodeEntity. But in cases where you need to store some data on the relationship itself, you have to declare it as a separate class with RelationshipEntity annotation, like that:

In this case, you have to also specify the StartNode and EndNode of relationship.

Repository

Now that you have all the above, you can start using the database. To do this you have to declare a Repository. Repositories are declared using an interface extending GraphRepository. Spring uses such interface to generate implementing class, that out of the box offers basic functionality like querying by Id, saving and deleting. You can easily add another query methods by just specifying correct names, like in an example below:

Summary

As you see, the theory is really simple, it does not require much of in-depth knowledge about graphs or Neo4j. All you need to know are simple basics and you can start using it.

I have added all these configuration steps from above to Commutee, but I have still some minor problems here and there, so the code is not on the GitHub yet, but as soon as I resolve them, I’ll push the code to the repository.

 

 


Also published on Medium.