This tutorial presents a well explained example application for using Spring Data Neo4j. In my previous article, I have explained about the Neo4j database installation in your Windows 7 system. Simply, it’s node and arcs; the nodes represent the business domain or entities, while the arcs works as a relationships between those defined entities.
For summarizing a many words that could be written about that subject, let’s see the below snapshots that show you the representation of User and Address entities associated each together using one relationship named address in the eyes of Neo4j.
- Within Neo4j database, the entities are formed using concept of nodes, where each of node has carried the properties and its represented types.
- By clicking on the node number 10, you will get a dialog shows you the properties and the type of that pressed node. As you see, that node is of type User and has the properties, status, age and fullName.
- Whereas the clicking on the node number 11, should provide you the details of an Address entity and the only one property that exhibited here is addressValue.
- The remaining one item that should highlighted is the relationship that correlate the User with it’s Address is called address and it doesn’t contain any properties. Graph Database has provided the concept of properties included in the defined relationship.
The proceeding in the explanation now is much easier than before this graphical introduction. So, Graph data consists of nodes connected with directed and labeled relationships. In property graphs, both nodes and relationships can hold arbitrary key/value pairs.
- As mentioned earlier, Neo4j is the leading implementation of a property graph database. It is written predominantly in Java and leverages a custom storage format and the facilities of the Java Transaction Architecture (JTA) to provide XA transactions.
- The Java API offers an object-oriented way of working with the nodes and relationships of the graph (show in the example). Traversals are expressed with a fluent API.
- Being a graph database, Neo4j offers a number of graph traversal algorithms like shortest path, Dijkstra, or A* out of the box.
The Neo4j has been coming into two main categories,
- Embedded Neo4j
- Standalone Neo4j Server that get accessed by using the HTTP protocol.
At this tutorial, I would explain both the concepts.
Spring Data Neo4j Configurations
- Before start writing your first application on Neo4j, you have to setup the Spring Container. The required configuration is depends on the type of the Neo4j that your application wants to use.
- Embedded Neo4j requires you providing a store directory, while the using of Standalone Neo4j server does require you connecting that server by providing the required connection data.
- Let’s see the second one while the first one isn’t long far from what you’ve been done when using the Standalone Neo4j server.
SpringContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:neo4j="http://www.springframework.org/schema/data/neo4j" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="net.javabeat.springdata.beans"></context:component-scan> <bean id="graphDatabaseService" class="org.springframework.data.neo4j.rest.SpringRestGraphDatabase"> <constructor-arg value="http://localhost:7474/db/data/" /> </bean> <neo4j:config graphDatabaseService="graphDatabaseService" /> <neo4j:repositories base-package="net.javabeat.springdata.repo" /> </beans>
- To start getting a neo4j into your Spring container, the namespace of neo4j should be imported.
- The well-known component-scan is provided for scanning the Spring Bean.
- The bean of graphDatabaseService should be used for connecting the Standalone neo4j server.
- The remaining neo4j:repositories and neo4j:config should be used for scanning the repositories being used later, and to configure the database service respectively.
Maven Dependencies For Spring Data Neo4j
The below is a pom.xml file that contains the all required library for Neo4j connection either Embedded or server.
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.javabeat.springdata</groupId> <artifactId>SpringData-JPA</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>Spring Data</name> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> <dependencies> <!-- SLF4J dependency --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> </dependency> <!-- Neo4j support for Spring Data --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-neo4j</artifactId> <version>2.3.5.RELEASE</version> </dependency> <!-- Advanced Mapping support for Spring Data Neo4j --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-neo4j-aspects</artifactId> <version>2.3.5.RELEASE</version> </dependency> <!-- Neo4j transaction library --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-neo4j-tx</artifactId> <version>2.3.5.RELEASE</version> </dependency> <!-- Required Libraries for Neo4j--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-neo4j-aspects</artifactId> <version>2.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-neo4j-rest</artifactId> <version>2.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.0.0.RELEASE</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.0.RELEASE</version> </dependency> <!-- Spring Data commons --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>1.5.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-asm</artifactId> <version>3.1.4.RELEASE</version> </dependency> </dependencies> </project>
Domain Class
Basically, the domain class will be containing two major entities, the User and the Address. Where the User has a direct association for the Address through address reference that marked as @RelatedTo.
User.java
package net.javabeat.springdata.jpa.data; import org.springframework.data.neo4j.annotation.GraphId; import org.springframework.data.neo4j.annotation.NodeEntity; import org.springframework.data.neo4j.annotation.RelatedTo; @NodeEntity public class User { @GraphId private Long id; private String fullName; private String age; private String status; @RelatedTo private Address address; public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String toString() { return this.id + "," + this.fullName; } }
Address.java
package net.javabeat.springdata.jpa.data; import org.springframework.data.neo4j.annotation.GraphId; import org.springframework.data.neo4j.annotation.NodeEntity; @NodeEntity public class Address { @GraphId private Long addressId; private String addressValue; public Long getAddressId() { return addressId; } public void setAddressId(Long addressId) { this.addressId = addressId; } public String getAddressValue() { return addressValue; } public void setAddressValue(String addressValue) { this.addressValue = addressValue; } }
- Neo4j provides many kinds of annotations that can be used for annotating the user defined classes
- @GraphId act like @Id, but this time is used for defining the node idenetifier property, which whose value is assigned by the container
- @RelatedTo used for defining the association (relationship) between two entities.
Defining Spring Data Repository
Spring Data provides the Spring developers an abstraction layer for dealing with the different types of database. The repository that you would have been seeing right now, is the same repository that already defined previously.
UserRepository.java
package net.javabeat.springdata.repo; import net.javabeat.springdata.jpa.data.User; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends CrudRepository<User, String>{}
- Nothing has been changed on the defined repository that used before
- @Repository annotation used for defining a Spring Data repository
Spring Data Neo4j Example Application
The executable application is just a sample standalone java application that provides the Spring Developer the most important code that should be used for defining and executing different operations against Neo4j graph database.
Executable.java
package net.javabeat.springdata.executable; import net.javabeat.springdata.beans.RegistrationBean; import net.javabeat.springdata.jpa.data.Address; import net.javabeat.springdata.jpa.data.User; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Executable { public static RegistrationBean registrationBean; public static ClassPathXmlApplicationContext context; static { // Acquire Context context = new ClassPathXmlApplicationContext("SpringContext.xml"); } public static void main(String [] args) throws Exception{ // Create User createUser(); } public static void createUser(){ User user = new User(); user.setFullName("Susa Richard"); user.setStatus("A"); user.setAge("30"); Address address = new Address(); address.setAddressValue("UK/Manchester"); user.setAddress(address); RegistrationBean bean = (RegistrationBean)context.getBean("registrationBean"); bean.getRepository().save(user); } }
Embedded Neo4j Graph Database
Regardless whether you have been installing the standalone neo4j server or not, the Embedded Neo4j should have been running smoothly. Simply, you have to change the Spring Context as below:
SpringContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:neo4j="http://www.springframework.org/schema/data/neo4j" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <neo4j:config storeDirectory="target/db" base-package="net.javabeat.springdata.jpa.data"/> <context:component-scan base-package="net.javabeat.springdata.beans"> </context:component-scan> <neo4j:repositories base-package="net.javabeat.springdata.repo" /> </beans>
The configuration provided above, specify the using of embedded by configuring the neo4j:config to store its data into store directory that already refers for real folder inside your project.
The application should have been working even if your Neo4j database standalone server has not started and your saved data should be located under the provided location in the storeDirecoty.
Summary
Spring Data provides convenient way to connect and store data to the Neo4j database using Spring Data Neo4j module. This article should provide the Spring Developer the mandatory information for connecting Neo4j through the standalone Neo4j database or by using its Embedded version. Hope this helps!!