Neo4j

Module 5. Spring
Level 17 , Lesson 6
Available

Neo4j is an open source NoSQL graph database that uses a full-featured data model of nodes connected by full relationships, which is better suited for linked big data than traditional RDBMS approaches. Spring Boot provides several helpers for working with Neo4j, including a "starter" spring-boot-starter-data-neo4j.

Connect to Neo4j database

To access the Neo4j server, you can implement the autoconfigurable org.neo4j.driver.Driver. By default, the instance will try to connect to the Neo4j server at localhost:7687 using the Bolt protocol. The following example shows how to implement a Driver for Neo4j, which will give access to, among other things, Session:

Java
import org.neo4j.driver.Driver;
import org.neo4j.driver.Session;
import org.neo4j.driver.Values;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
    private final Driver driver;
    public MyBean(Driver driver) {
        this.driver = driver;
    }
 // ...
 public String someMethod(String message) {
        try (Session session = this.driver.session()) {
            return session.writeTransaction((transaction) -> transaction
                    .run("CREATE (a:Greeting) SET a.message = $message RETURN a.message + ', from node ' + id(a)",
                            Values.parameters("message", message))
                    .single().get(0).asString());
        }
    }
}
Kotlin
import org.neo4j.driver.Driver
import org.neo4j.driver.Transaction
import org.neo4j.driver.Values
import org.springframework.stereotype.Component
@Component
class MyBean(private val driver: Driver) {
 // ...
 fun someMethod(message: String?): String {
        driver.session().use { session ->
            return@someMethod session.writeTransaction { transaction: Transaction ->
                transaction.run(
                    "CREATE (a:Greeting) SET a.message = \$message RETURN a.message + ', from node ' + id(a)",
                    Values.parameters("message", message)
                ).single()[0].asString()
            }
        }
    }
}

You can add various aspects of the driver to the configuration using the spring.neo4j.* properties. The following example shows how to configure the URI and credentials to use:

Properties
spring.neo4j.uri=bolt://my-server:7687
spring.neo4j.authentication.username=neo4j
spring.neo4j.authentication.password=secret
Yaml
spring:
  neo4j:
    uri: "bolt://my-server:7687"
    authentication:
      username: "neo4j"
      password: "secret"

Autoconfigurable Driver is created using ConfigBuilder. To fine-tune its configuration, declare one or more ConfigBuilderCustomizer beans. Each of them will be called in order through the ConfigBuilder, which is used to create the Driver.

Spring Data Neo4j repositories

Spring Data contains repository support for Neo4j.

Spring Data Neo4j shares the Spring Data JPA infrastructure, as do many other Spring Data modules. You can take the JPA example from the previous section and define City as @Node for Spring Data Neo4j rather than @Entity for JPA, while abstracting storage will work exactly as shown in the following example:

Java
import java.util.Optional;
import org.springframework.data.neo4j.repository.Neo4jRepository;
public interface CityRepository extends Neo4jRepository<City, Long> {
    Optional<City> findOneByNameAndState(String name, String state);
}
Kotlin
import org.springframework.data.neo4j.repository.Neo4jRepository
import java.util.Optional
interface CityRepository : Neo4jRepository<City?, Long?> {
    fun findOneByNameAndState(name: String?, state: String?): Optional<City?>?
}

"Starter" spring-boot-starter-data-neo4j enables support for repositories, as well as transaction management. Spring Boot supports both classic and reactive Neo4j repositories through the Neo4jTemplate or ReactiveNeo4jTemplate beans. If Project Reactor is available in the classpath, the reactive style is also automatically configured.

You can configure the locations where repositories and entities will be searched using the @EnableNeo4jRepositories and @EntityScan annotations, respectively, on a bean marked with the @Configuration annotation code>.

In an application using the reactive style, ReactiveTransactionManager is not automatically configured. To enable transaction management, the following bean must be defined in the configuration:

Java
import org.neo4j.driver.Driver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.core.ReactiveDatabaseSelectionProvider;
import org.springframework.data.neo4j.core.transaction.ReactiveNeo4jTransactionManager;
@Configuration(proxyBeanMethods = false)
public class MyNeo4jConfiguration {
    @Bean
    public ReactiveNeo4jTransactionManager reactiveTransactionManager(Driver driver,
            ReactiveDatabaseSelectionProvider databaseNameProvider) {
        return new ReactiveNeo4jTransactionManager(driver, databaseNameProvider);
    }
}
Kotlin
import org.neo4j.driver.Driver
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.neo4j.core.ReactiveDatabaseSelectionProvider
import org.springframework.data.neo4j.core.transaction.ReactiveNeo4jTransactionManager
@Configuration(proxyBeanMethods = false)
class MyNeo4jConfiguration {
    @Bean
    fun reactiveTransactionManager(driver: Driver,
            databaseNameProvider: ReactiveDatabaseSelectionProvider): ReactiveNeo4jTransactionManager {
        return ReactiveNeo4jTransactionManager(driver, databaseNameProvider)
    }
}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION