Skip to content

Provides support to increase developer productivity in Java when using the neo4j graph database. Uses familiar Spring concepts such as a template classes for core API usage and provides an annotation based programming model using AspectJ

Notifications You must be signed in to change notification settings

Richterrettich/spring-data-neo4j

 
 

Repository files navigation

Spring Data Neo4j – Quick start

@NodeEntity
class Person {
    @Indexed
    private String name;

    @RelatedTo(direction = Direction.BOTH, elementClass = Person.class)
    private Set<Person> friends;

    public Person() {}
    public Person(String name) { this.name = name; }

    private void knows(Person friend) { friends.add(friend); }
}

Person jon = new Person("Jon").persist();
Person emil = new Person("Emil").persist();
Person rod = new Person("Rod").persist();

emil.knows(jon);
emil.knows(rod);

// Persist created relationships to graph database
emil.persist();

for (Person friend : emil.getFriends()) {
    System.out.println("Friend: " + friend);
}

// Method findAllByTraversal() is one of the methods introduced by @NodeEntity
for (Person friend : jon.findAllByTraversal(Person.class,
        Traversal.description().evaluator(Evaluators.includingDepths(1, 2)))) {
    System.out.println("Jon's friends to depth 2: " + friend);
}

// Add <datagraph:repositories base-package="com.example.repo"/> to context config.
interface com.example.repo.PersonRepository extends GraphRepository<Person> {}

@Autowired PersonRepository repo;
emil = repo.findByPropertyValue("name", "emil");
long numberOfPeople = repo.count();

About

The primary goal of the Spring Data project is to make it easier to build Spring-powered applications that use new data access technologies such as non-relational databases, map-reduce frameworks, and cloud based data services. As the name implies, the Graph project provides integration with graph value stores. The only supported Graph Database now is Neo4j.

The Spring Data Neo4j project provides a simplified POJO based programming model that reduces that amount of boilerplate code needed to create neo4j applications. It also provides a cross-store persistence solution that can extend existing JPA data models with new parts (properties, entities, relationships) that are stored exclusively in the graph while being transparently integrated with the JPA entities. This enables for easy and seamless addition of new features that were not available before to JPA-based applications.

Maven configuration

  • Add the maven repository and dependency:
<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-neo4j</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>
</dependencies>
<repositories>
    <repository>
        <id>spring-maven-snapshot</id>
        <snapshots><enabled>true</enabled></snapshots>
        <name>Springframework Maven MILESTONE Repository</name>
        <url>http://maven.springframework.org/milestone</url>
    </repository>
</repositories>
  • Configure AspectJ: Include the following plugin XML in your pom.xml to hook AspectJ into the build process:
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.4</version>
            <configuration>
                <outxml>true</outxml>
                <aspectLibraries>
                    <aspectLibrary>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-aspects</artifactId>
                    </aspectLibrary>
                    <aspectLibrary>
                        <groupId>org.springframework.data</groupId>
                        <artifactId>spring-data-neo4j</artifactId>
                    </aspectLibrary>
                </aspectLibraries>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjrt</artifactId>
                    <version>1.7.4</version>
                </dependency>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjtools</artifactId>
                    <version>1.7.4</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

Spring configuration

  • Configure Spring Data Neo4j for Neo4j in your application using the provided XML namespace:
<?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: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:spring-configured/>
    <context:annotation-config/>
    <context:component-scan base-package="org.springframework.data.neo4j.examples.hellograph" />

    <neo4j:config storeDirectory="target/neo4j-db-plain"
                  base-package="org.springframework.data.neo4j.examples.hellograph.domain"/>
    <neo4j:repositories base-package="org.springframework.data.neo4j.examples.hellograph.repositories"/>

    <tx:annotation-driven />
</beans>

Graph entities

  • Annotate your entity class. In this case it is a ‘World’ class that has a relationship to other worlds that are reachable by rocket travel:
@NodeEntity
public class World {

    // Uses default schema based index
    @Indexed
    private String name;

    // Uses legacy index mechanism
    @Indexed(indexType = IndexType.SIMPLE)
    private int moons;

    @RelatedTo( type = "REACHABLE_BY_ROCKET", direction = Direction.BOTH, elementClass = World.class )
    private Set<World> reachableByRocket;

    public World() {}
    public World(String name, int moons) {
        this.name = name;
        this.moons = moons;
    }

    public String getName()  { return name; }

    public int getMoons() { return moons; }

    public void addRocketRouteTo( World otherWorld ) {
        reachableByRocket.add( otherWorld );
    }

    public boolean canBeReachedFrom( World otherWorld ) {
        return reachableByRocket.contains( otherWorld );
    }
}

Transactional services

  • Create a repository or service to perform typical operations on your entities. The complete functionality is covered in the reference manual.
public interface WorldRepository extends GraphRepository<World> {}

@Service
@Transactional
public class GalaxyService {

    @Autowired
    private WorldRepository worldRepository;

    public long getNumberOfWorlds() {
        return worldRepository.count();
    }

    public World createWorld(String name, int moons) {
        return worldRepository.save(new World(name, moons));
    }

    public Iterable<World> getAllWorlds() {
        return worldRepository.findAll();
    }

    public World findWorldById(Long id) {
        return worldRepository.findOne(id);
    }

    // This is using the schema based index
    public World findWorldByName(String name) {
        return worldRepository.findBySchemaPropertyValue("name", name);
    }

    // This is using the legacy index
    public Iterable<World> findAllByNumberOfMoons(int numberOfMoons) {
        return worldRepository.findAllByPropertyValue("moons", numberOfMoons);
    }

    public Collection<World> makeSomeWorlds() {
        Collection<World> worlds = new ArrayList<World>();

        // Solar worlds
        worlds.add(createWorld("Mercury", 0));
        worlds.add(createWorld("Venus", 0));

        World earth = createWorld("Earth", 1);
        World mars = createWorld("Mars", 2);
        mars.addRocketRouteTo(earth);
        worldRepository.save(mars);
        worlds.add(earth);
        worlds.add(mars);

        // ... Create more worlds

        return worlds;
    }

}

Please see the Hello Worlds sample project in the examples repository for more information.

Getting Help

This README and the User Guide are the best places to start learning about Spring Data Neo4j. There are also three sample applications briefly described in the reference documentation.

The main project website contains links to basic project information such as source code, JavaDocs, Issue tracking, etc.

For more detailed questions, use the forum. If you are new to Spring as well as to Spring Data, look for information about Spring projects.

Contributing to Spring Data

Here are some ways for you to get involved in the community:

  • Get involved with the Spring community on the Spring Community Forums. Please help out on the forum by responding to questions and joining the debate.
  • Create JIRA tickets for bugs and new features and comment and vote on the ones that you are interested in.
  • Github is for social coding: if you want to write code, we encourage contributions through pull requests from forks of this repository. If you want to contribute code this way, please reference a JIRA ticket as well covering the specific issue you are addressing.
  • Watch for upcoming articles on Spring by subscribing to springframework.org

Before we accept a non-trivial patch or pull request we will need you to sign the contributor’s agreement. Signing the contributor’s agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join the core team, and given the ability to merge pull requests.

About

Provides support to increase developer productivity in Java when using the neo4j graph database. Uses familiar Spring concepts such as a template classes for core API usage and provides an annotation based programming model using AspectJ

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java 97.3%
  • CSS 1.6%
  • Other 1.1%