Hot questions for Using Neo4j in driver

Question:

I have some logic which needs direct node access to neo4j but the rest of the app using Spring Data Neo4j (SDN) for simplicity. I thought to use a procedure with @Procedure, but I'm not sure how to use that procedure when using the neo4j embedded driver and SDN4. My configuration is very barebones as below:

@Configuration
@EnableNeo4jRepositories(basePackages = "recommender.repository")
@ComponentScan(basePackages = "recommender")
@EnableTransactionManagement
public class MyNeo4jConfiguration extends Neo4jConfiguration {

@Bean
public SessionFactory getSessionFactory() {

    System.out.println("******* GET SESSION FACTORY!!!!");
    // with domain entity base package(s)
    return new SessionFactory("recommender.model");
}

// needed for session in view in web-applications
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
    return super.getSession();
}

With a property file here:

#EmbeddedSetup
driver=org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
#URI=file:/neo4j/data/graph.db

With that setup where can I place the class with @Procedure and @Context (for the db access) where SDN's implementation has access to it during war deployment.


Answer:

SDN itself has no functionality to manage procedures for you. However, there is a way to access the underlying GraphDatabaseService:

 EmbeddedDriver embeddedDriver = (EmbeddedDriver) Components.driver();
 GraphDatabaseService databaseService = embeddedDriver.getGraphDatabaseService();

Using this, you can register your procedure

((GraphDatabaseAPI) getDatabase()).getDependencyResolver().resolveDependency(Procedures.class).register(YourProcedure.class);

However, not really sure if this works with your procedure class in the application classpath- worth trying though.

Question:

I'm having issues getting the minimal viable snippet for the Neo4J-jdbc driver working. I'm using intelliJ idea with gradle. When I import org.neo4j.jdbc.*;, DriverManager cannot be resolved and there are multiple occurences of Unhandled Exception: java.sql.SQLException. When I import java.sql.*, there are more java.sql.SQLException errors. When I import both, there are multiple errors as the references are ambigious between the two libraries.

The minimal viable snippet in the official documentation is as follows:

// Connecting
try (Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost", 'neo4j', password)) {

    // Querying
    String query = "MATCH (u:User)-[:FRIEND]-(f:User) WHERE u.name = {1} RETURN f.name, f.age";
    try (PreparedStatement stmt = con.prepareStatement(query)) {
        stmt.setString(1,"John");

        try (ResultSet rs = stmt.execute()) {
            while (rs.next()) {
                System.out.println("Friend: "+rs.getString("f.name")+" is "+rs.getInt("f.age"));
            }
        }
    }
}

Gradle dependencies:

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.neo4j', name: 'neo4j-jdbc-bolt', version: '3.1.0'
    compile 'com.sparkjava:spark-core:2.3'
}

I'm really looking for a minimal implementation here, I'm just curious as to what I'm missing out on to get the minimal snippet working.


Answer:

You need to import java.sql.* and that's all.Yes you will have some SQLException, but you just have to handle them in a catch or by adding the exception in your method signature (like below).

There is one mistake on the snippet, the stmt.execute() returns a boolean and not a ResultSet, so you need to replace it by stmt.executeQuery().

This is a complete/working example :

import java.sql.*;

public class JDBCTest {

  public static void main() throws SQLException {

        // Connecting
        try (Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost", "neo4j", "admin")) {

            // Querying
            String query = "MATCH (u:User)-[:FRIEND]-(f:User) WHERE u.name = {1} RETURN f.name, f.age";
            try (PreparedStatement stmt = con.prepareStatement(query)) {
                stmt.setString(1,"John");

                try (ResultSet rs = stmt.executeQuery()) {
                    while (rs.next()) {
                        System.out.println("Friend: "+rs.getString("f.name")+" is "+rs.getInt("f.age"));
                    }
                }
            }
        }
    }
}

Question:

I get this error from Spring Boot.

Could not deduce driver to use based on URI 'bolt://localhost:7687

when attempting to configure with properties, or env variable

spring.data.neo4j.uri=bolt://localhost:7687

I did add the driver

   <dependency>
        <scope>runtime</scope>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-ogm-bolt-driver</artifactId>
        <version>${neo4j-ogm.version}</version>
    </dependency>

I imagine spring boot doesn't support autoconfiguration for this yet

How can I set this driver up manually to work with Spring Boot / Data? please provide an example.


Answer:

The current Spring Boot starter for Neo4j does not detect the bolt protocol and so cannot autoconfigure the Bolt driver. However, if you supply a Configuration bean in your application context, Spring Boot will use that, and not attempt to autoconfigure the driver itself.

This should be enough to get you going:

@Bean
public Configuration getConfiguration() {
   Configuration config = new Configuration();
   config
       .driverConfiguration()
       .setURI("bolt://localhost");
   return config;
}

Note that you don't need to declare the driver name in the configuration, it will be autodetected from the URI.

Also, note the Configuration class is actually org.neo4j.ogm.config.Configuration, which you'll probably need to use explicitly.

Question:

I am unable to run any queries on Neo4J after I have updated my neo4j-java-driver from 1.0.5 to 1.7.2.

<dependency>
    <groupId>org.neo4j.driver</groupId>
    <artifactId>neo4j-java-driver</artifactId>
    <version>1.7.2</version>
</dependency>
@Test
public void test2(){
    Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("aaa", "bbb"));
    try (Session session = driver.session()) {
      session.run("MATCH (movie:Movie {title:{title}})" +
                                        " OPTIONAL MATCH (movie)<-[r]-(person:Person)\n" +
                                        " RETURN movie.title as title, collect({name:person.name, job:head(split(lower(type(r)),'_')), role:r.roles}) as cast LIMIT 1",
                        map("title", "The Matrix"));
    }
    driver.close();
}

The test above works with 1.0.5 version but fails with the 1.7.2 version with the following error:

org.neo4j.driver.v1.exceptions.UntrustedServerException: Server provides no product identifier

Does anyone know of a sample that works with this new driver version in the vein of the https://github.com/neo4j-examples/neo4j-movies-java-bolt sample for the previous driver?


Answer:

The driver 1.7 is compatible with server version 3.5, 3.4 & 3.3.

So if you use this driver with a server version that is not in the list, you will have the exception UntrustedServerException

Question:

I am trying to find out execution time of my Cypher query with java driver.

Session session = driver.session();
session.run( "CREATE (a:Person {name:'Arthur', title:'King'})" );
StatementResult result = session.run( "Profile MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title" );

But I could not find it anywhere in the StatementResult or in the ResultSummary, which is returned by StatementResult.consume(query).

I could access db hits from ProfiledPlan in ResultSummary but there is no information about time.

Is there any way I can access Cypher query execution time using neo4j java driver?


Answer:

Since Neo4j Java driver version 1.1.0 there is:

/**
 * The time it took the server to make the result available for consumption.
 *
 * @param unit The unit of the duration.
 * @return The time it took for the server to have the result available in the provided time unit.
 */
long resultAvailableAfter( TimeUnit unit );

/**
 * The time it took the server to consume the result.
 *
 * @param unit The unit of the duration.
 * @return The time it took for the server to consume the result in the provided time unit.
 */
long resultConsumedAfter( TimeUnit unit );

It provides you with both times:

  1. Time till first byte
  2. Full execution time including consuming data from server

Methods are localted on org.neo4j.driver.v1.summary.ResultSummary interface.

Question:

Hello everybody!

I have developed a JavaFX application to support my scientific work (molecular biology/neuropharmacology), implementing Neo4j, at the time Version 2.x.

Now, since Version 3 (using 3.1.0-M05) is out, I am switching over to Bolt protocol access of the Database, with the Driver (1.1.0-M01) interface. Some functions of my application still require Java API access though, so I cannot completely abandon the old code. I am using a singleton GraphDatabaseFactory to start up the database, like so

private static GraphDatabaseService instance;

private GraphDb() {
    instance = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(new File(FilePaths.DATABASE_PATH))
            .setConfig(ShellSettings.remote_shell_enabled, "true").newGraphDatabase();
}

public static synchronized GraphDatabaseService getInstance() {
    return instance;
}

(Or, just the .newEmbeddedDatabase())But now, since Version 3, I also use a singleton Driver instance for the Bolt interaction, like so

private static Driver instance;

private GraphDbDriver() {
    startLocalDb();
    instance = GraphDatabase.driver("bolt://localhost");
}

private static void startLocalDb() {
//start database here?
}


public static synchronized Driver getInstance() {
    return instance;
}

My question now, is this (since I gathered that using both at the same time can only breed complications): How do I use these two ways of communicating with the DB without them getting in the way of each other?

Can I somehow get the Driver to load "onto" the already created GraphDatabaseService singleton?

Thanks for reading!


Answer:

So, for anybody who's interested, in Neo4j 3.x it is recommended to use 'User-defined procedures' to implement API commands (like, e.g., traversals) and then calling it (via CALL) from cypher.

Question:

I'm trying to create a node that has many properties using the Neo4j Java Bolt driver. My code currently looks like this:

String statement =                                                        
      "   CREATE (p:Person {id: {id}, firstName: {firstName}, lastName: {lastName}, gender: {gender}, birthday: {birthday}, creationDate: {creationDate}, locationIp: {locationIp}, browserUsed: {browserUsed}, speaks: {speaks}, emails: {emails}})";
String parameters = parameters(                                           
      "id", String.valueOf(operation.personId()),                           
      "firstName", operation.personFirstName(),                             
      "lastName", operation.personLastName(),                               
      "gender", operation.gender(),                                         
      "birthday", operation.birthday().getTime(),                           
      "creationDate", operation.creationDate().getTime(),                   
      "locationIP", operation.locationIp(),                                 
      "browserUsed", operation.browserUsed(),                               
      "speaks", operation.languages(),                                      
      "emails", operation.emails());

  try (Session session = driver.session(AccessMode.WRITE)) {                 
    try (Transaction tx = session.beginTransaction()) {                     
      StatementResult result = tx.run(statement, params);                   
      tx.success();                                                         
      tx.close();                                                           
    }                                                                       
  }

But using HTTP and JSON, it's possible to simplify the statement to:

String statement =                                                        
      "   CREATE (p:Person {props})";

And send a JSON object that's something like:

{props: 
    {id: bla, 
     firstName: bla,
     lastName: bla,
     ...
     }
}

Is there a way in the Neo4j Bolt driver API to use this latter version of the CREATE statement and supply parameters as a map?


Answer:

That's independent of the API. The CREATE (p:Person {props}) syntax was deprecated in favour of:

CREATE (p:Person) SET p = {props}

or if you want to be additive

CREATE (p:Person) SET p += {props}

You can also set multiple at once.

see: https://neo4j.com/docs/developer-manual/current/cypher/clauses/create/#create-create-node-with-a-parameter-for-the-properties

With the bolt driver you sent a map along. or Values.parameters("id", id, "firstName", firstname, ...)

Question:

I am using Neo4j Community Edition for my application that uses Spring Boot.

My Neo4j context looks like this

@Configuration
@EnableTransactionManagement
@EnableNeo4jRepositories(basePackages = { "com.lapots.tree.model.repository" })
public class Neo4jPersistenceContext {

    @Bean
    public SessionFactory sessionFactory() {
        return new SessionFactory("com.lapots.tree.model.domain.graph");
    }

    @Bean
    public Neo4jTransactionManager transactionManager() {
        return new Neo4jTransactionManager(sessionFactory());
    }
}

And repository looks like this

@Repository
public interface IDialogLineRepository extends Neo4jRepository<DialogLine, String> {

    Collection<DialogLine> findByOwner(String owner);
}

I set couple of properties for the application

spring.data.neo4j.uri=bolt://127.0.0.1:7687
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=admin

During the startup the application fails with

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dialogLineService': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyExceptio
n: Error creating bean with name 'IDialogLineRepository': Unsatisfied dependency expressed through method 'setSession' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.d
ata.neo4j.transaction.SharedSessionCreator#0': Cannot resolve reference to bean 'sessionFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defi
ned in class path resource [com/lapots/tree/model/repository/context/Neo4jPersistenceContext.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.ses
sion.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:358) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1337) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:574) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:491) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:806) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:349) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1289) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
        at com.lapots.tree.model.web.TreeModelSystemApplication.main(TreeModelSystemApplication.java:17) [main/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'IDialogLineRepository': Unsatisfied dependency expressed through method 'setSession' parameter 0; nested exception is org.springframework.beans.factory.B
eanCreationException: Error creating bean with name 'org.springframework.data.neo4j.transaction.SharedSessionCreator#0': Cannot resolve reference to bean 'sessionFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [com/lapots/tree/model/repository/context/Neo4jPersistenceContext.class]: Bean instantiation via factory method failed; nested exception is org.springframework.
beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: org.neo4j.ogm.drivers.embedded.dri
ver.EmbeddedDriver
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:652) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:358) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1337) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:574) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:491) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:250) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1128) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1056) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:570) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        ... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.data.neo4j.transaction.SharedSessionCreator#0': Cannot resolve reference to bean 'sessionFactory' while setting constructor argument; nested e
xception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [com/lapots/tree/model/repository/context/Neo4jPersistenceContext.class]: Bean instantiation via factory method fa
iled; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoun
dException: org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:633) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:447) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1246) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1093) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:534) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:491) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:250) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1128) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1056) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:644) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        ... 37 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [com/lapots/tree/model/repository/context/Neo4jPersistenceContext.class]: Bean instantiation via factory method fai
led; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFound
Exception: org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:598) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1246) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1093) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:534) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:491) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        ... 52 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: org
.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        ... 61 common frames omitted
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
        at org.neo4j.ogm.driver.DriverManager.register(DriverManager.java:24) ~[neo4j-ogm-api-3.0.0-M01.jar:na]
        at org.neo4j.ogm.session.SessionFactory.<init>(SessionFactory.java:74) ~[neo4j-ogm-core-3.0.0-M01.jar:na]
        at org.neo4j.ogm.session.SessionFactory.<init>(SessionFactory.java:52) ~[neo4j-ogm-core-3.0.0-M01.jar:na]
        at com.lapots.tree.model.repository.context.Neo4jPersistenceContext.sessionFactory(Neo4jPersistenceContext.java:17) ~[main/:na]
        at com.lapots.tree.model.repository.context.Neo4jPersistenceContext$$EnhancerBySpringCGLIB$$397cc60b.CGLIB$sessionFactory$1(<generated>) ~[main/:na]
        at com.lapots.tree.model.repository.context.Neo4jPersistenceContext$$EnhancerBySpringCGLIB$$397cc60b$$FastClassBySpringCGLIB$$1006188e.invoke(<generated>) ~[main/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-5.0.0.RC1.jar:5.0.0.RC1]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-5.0.0.RC1.jar:5.0.0.RC1]
        at com.lapots.tree.model.repository.context.Neo4jPersistenceContext$$EnhancerBySpringCGLIB$$397cc60b.sessionFactory(<generated>) ~[main/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-5.0.0.RC1.jar:5.0.0.RC1]
        ... 62 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_121]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_121]
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_121]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_121]
        at java.lang.Class.forName0(Native Method) ~[na:1.8.0_121]
        at java.lang.Class.forName(Class.java:264) ~[na:1.8.0_121]
        at org.neo4j.ogm.driver.DriverManager.register(DriverManager.java:21) ~[neo4j-ogm-api-3.0.0-M01.jar:na]
        ... 75 common frames omitted

My build.gradle looks like this

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
apply plugin: 'org.junit.platform.gradle.plugin'

mainClassName='com.lapots.tree.model.web.TreeModelSystemApplication'
sourceCompatibility = 1.8

run {
    standardInput = System.in
}

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
}

configurations {
    providedRuntime
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-webflux')
    compile('org.springframework.boot:spring-boot-starter-websocket')
    compile('org.springframework.data:spring-data-neo4j')
    compile('org.neo4j:neo4j-ogm-core')

    runtime('org.neo4j:neo4j-ogm-bolt-driver')
    runtime('org.springframework.boot:spring-boot-devtools')

    compileOnly('org.projectlombok:lombok')

    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile("org.junit.jupiter:junit-jupiter-engine:$junitJupiterEngineVersion")
    testCompile("org.junit.jupiter:junit-jupiter-api:$junitJupiterApiVersion")
}

Specifically I have this dependencies for Neo4j

compile('org.springframework.data:spring-data-neo4j')
compile('org.neo4j:neo4j-ogm-core')
runtime('org.neo4j:neo4j-ogm-bolt-driver')

Additionally I set the property spring.data.neo4j.embedded.enabled=false to prevent using embedded database. However it seems it still requires driver for embedded driver. Why is that?


Answer:

Accoroding to the document SessionFactory uses embeddedDriver by default when configuration is not provided.

So I just provided the configuration and it did the trick

@Value("${spring.data.neo4j.uri}")
private String databaseUrl;

@Value("${spring.data.neo4j.username}")
private String userName;

@Value("${spring.data.neo4j.password}")
private String password;

@Bean
public SessionFactory sessionFactory() {
    Configuration configuration = new Configuration.Builder()
            .uri(databaseUrl)
            .credentials(userName, password)
            .build();
    return new SessionFactory(configuration, "com.lapots.tree.model.domain.graph");
}

Question:

I am currently using the new SDN 4 ogm.properties file to configure the HttpDriver and was going to test with the new Neo4J 3.0 version. Has the new Bolt driver been released yet to test with or is there a scheduled release date for it? Currently the documentation only lists the Http or Embedded options.


Answer:

No, the Bolt driver is work in progress. It'll be released when Neo4j 3.0 is out. We don't have scheduled dates for milestone releases yet.

Question:

We a trying to connect neo4j using neo4j-jdbc driver with Java. The code we are trying to apply .

    try {
        Class.forName("org.neo4j.jdbc.Driver");
        // Conne

        System.out.println("GreetingServiceImpl.greetServer()");

        Connection connect =  DriverManager.getConnection("jdbc:neo4j://localhost:7474/","neo4j","password");

        Statement stmt = connect.createStatement();
        String q = "MATCH (n:Question) RETURN n LIMIT 25";

        ResultSet rs = stmt.executeQuery(q);
        while(rs.next())
        {
            System.out.println(rs.getString("n.QuesID"));
        }
    } catch (Exception e) {
        // TODO: handle exception
        System.out.println("bhalu");
        e.printStackTrace();
    }

We are using the neo4j-jdbc jar version 2.3.1. But now the problem is the dependencies of neo4j-jdbc jar. We are unable to find the dependencies jar and its continuously giving error.

    Feb 11, 2016 12:17:06 PM org.neo4j.jdbc.Driver createDatabases
     WARNING: Embedded Neo4j support not enabled        
 org/neo4j/graphdb/GraphDatabaseService
    **com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String com.client.GreetingService.graphtheory() throws java.lang.IllegalArgumentException' threw an unexpected exception:** java.lang.NoClassDefFoundError: org/neo4j/cypherdsl/grammar/Execute
    at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:389)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:579)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:265)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:305)
    at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:686)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:501)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at    org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:108 6)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:68)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.Server.handle(Server.java:370)
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
    at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:960)
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1021)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:668)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: org/neo4j/cypherdsl/grammar/Execute
    at org.neo4j.jdbc.Driver.<init>(Driver.java:63)
    at org.neo4j.jdbc.Driver.<clinit>(Driver.java:46)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:191)
    at com.server.GreetingServiceImpl.graphtheory(GreetingServiceImpl.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:561)
    ... 30 more
**Caused by: java.lang.ClassNotFoundException: org.neo4j.cypherdsl.grammar.Execute**
    at java.lang.ClassLoader.findClass(ClassLoader.java:531)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:407)
    at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:383)
    ... 40 more

Even downloaded the org/neo4j/cypherdsl/grammar/Execute jar but the grammar package is missing. We want to code for neo4j in java without any maven dependencies. So, how can we find the depended jars?


Answer:

What is you build config? Please try 2.3.2 of neo4j-jdbc

I don't understand why you don't want the dependencies,

but here you can see all jars that are generated by the build including your non-dependency-jar: https://m2.neo4j.org/content/repositories/releases/org/neo4j/neo4j-jdbc/2.3.2/

Question:

I am using Ne04j v3.1.0 with the Java driver. I am having trouble getting the results of an update statement (cypher SET) within an explicit transaction to persist. Returned values from within the transaction show the change, but after the transaction has ended the change seems to be gone. I know that updates are sensitive to results processing

[http://neo4j.com/docs/developer-manual/current/drivers/process-results/][1]

so I have been aggressive in my code about consuming all results and closing my sessions.

I wrote a test program to demonstrate the problem:

package uk.co.scapps.createdirs.neo;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;


public class Trans {
    static Driver driver = GraphDatabase.driver("bolt://localhost", AuthTokens.basic("neo4j", "neo4k"));
    static Session session = driver.session();
    final static Logger logger = LogManager.getLogger();

    public static void main(String[] args) {
        session = driver.session();
        StatementResult results ;
        session = driver.session();
        try (Transaction tx = session.beginTransaction()) {
            results = tx.run("MATCH (n:THING) RETURN n.name as name");
            while (results.hasNext()) {
                Record record = results.next();
                System.out.println("in the txn before the update: " + record.get("name").toString());
            }           
            results.consume();
            results = tx.run("MATCH (n:THING {name: 'a'}) SET n.name = 'asdasd' RETURN n.name as name");
            while (results.hasNext()) {
                Record record = results.next();
                System.out.println("results returned from the update: " + record.get("name").toString());
            }           
            results.consume();
            results = tx.run("MATCH (n:THING) RETURN n.name as name");
            while (results.hasNext()) {
                Record record = results.next();
                System.out.println("after the update but still in the txn: " + record.get("name").toString());
            }           
            results.consume();
            tx.close();
            session.close();
        }
        session = driver.session();
        results = session.run("MATCH (n:THING) RETURN n.name as name");
        while (results.hasNext()) {
            Record record = results.next();
            System.out.println("after the txn: " + record.get("name").toString());
        }           
        results.consume();
        session.close();
    }
}

And here is the output:

in the txn before the update: "a"
in the txn before the update: "b"
in the txn before the update: "c"
results returned from the update: "asdasd"
after the update but still in the txn: "asdasd"
after the update but still in the txn: "b"
after the update but still in the txn: "c"
after the txn: "a"
after the txn: "b"
after the txn: "c"

I haven't included the code, but I wrote a non-transactional (implicit transactional) version of the program and it works as expected.

I would appreciate any help.


Answer:

I had failed to execute txn.success().

Question:

I am using Neo4j java driver 1.7.5. I noticed that after successive calls, the number of Neo4jDriverIO threads is increasing until it achieves the max number of 2 * CPUs.

Is there a way to control the number of Neo4jDriverIO threads ? Is this max number 2 * CPUs a normal default configuration ?

Thanks.


Answer:

According to Neo4j java driver maintainers, the max number of 2 * CPUs Neo4jDriverIO threads is the default behavior. It will be possible to control the number of threads starting with incoming 4.0.0 java driver version. See this discussion.

Question:

I'm connecting with Java to neo4j using the GraphDatabase.driver and I have this log4j.properties file which suppresses the output of HBase and MongoDB but doesn't work with neo4j:

log4j.rootLogger=OFF, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n

The logging output that shows up in the client application looks like this:

Mär 15, 2018 11:20:03 AM org.neo4j.driver.internal.logging.JULogger info
INFORMATION: Closing driver instance org.neo4j.driver.internal.InternalDriver@6743e411
Mär 15, 2018 11:20:03 AM org.neo4j.driver.internal.logging.JULogger info
INFORMATION: Closing connection pool towards localhost:7687
Mär 15, 2018 11:20:05 AM org.neo4j.driver.internal.logging.JULogger info

How can this be disabled?


Answer:

The JULogger of the neo4j GraphDatabase.driver can be disabled using the java.util.logging.LogManager

LogManager.getLogManager().reset();

This will disable the logging, thus even suppress error messages. If just the INFO message shown in the example output should be suppressed then the log level has to be changed.

Logger rootLogger = LogManager.getLogManager().getLogger("");
rootLogger.setLevel(Level.SEVERE);
for (Handler h : rootLogger.getHandlers())
    h.setLevel(Level.SEVERE);

Question:

I already checked the other question about my issue, but none of them solved. I imported the Neo4j Jar by configuring the build path, but still I get this error.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestNeo4j {

	public static void main(String[] args) throws SQLException {
		
		
		Connection c = DriverManager.getConnection("jdbc:neo4j://localhost:7474/", "neo4j", "neo4j");
		Statement st = c.createStatement();
		String cql = "match (m)-[:IS_ALLERGIC_TO]->(n:Product) where n.name = 'gluten' return m.name";
		ResultSet rs = st.executeQuery(cql);
		while(rs.next())
			System.out.println(rs.getString(1));
		
		c.close();
	
	
	}

}

Answer:

As suggested here, use neo4j jar with dependencies (neo4j-jdbc-2.1.4-jar-with-dependencies.jar).

You can grab it from neo4j release repository, here

Question:

Is it possible to connect to an embedded Neo4j database the same way you would do with an H2 in-memory database to mock an Oracle database?

I've tried to do this:

final BoltConnector boltConnector = new BoltConnector("bolt");
graphDb = new GraphDatabaseFactory()
        .newEmbeddedDatabaseBuilder(DB_PATH)
        .setConfig(boltConnector.type, BOLT.name())
        .setConfig(boltConnector.enabled, TRUE)
        .setConfig(boltConnector.listen_address, listenAddress("127.0.0.1", 7688))
        .setConfig(boltConnector.encryption_level, DISABLED.name())
        .setConfig(GraphDatabaseSettings.auth_enabled, FALSE)
        .newGraphDatabase();

And then make a request using the JDBC Bolt driver with the following spring.datasource configuration:

spring:
  profiles: test
  datasource:
    driver-class-name: org.neo4j.jdbc.bolt.BoltDriver
    url: jdbc:neo4j:bolt://127.0.0.1:7688/?nossl

But I always get the following error:

Unable to connect to 127.0.0.1:7688, ensure the database is running and that there is a working network connection to it.

Of course the embedded database works when I use the graphDb instance and execute requests against it. But I want my application to connect to the embedded database as it does when connecting to a remote Neo4j database. This is for testing purpose.


Answer:

I finally RTFM... I had the following dependency in my pom.xml:

<dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j</artifactId>
    <version>3.4.0</version>
</dependency>

Then I found this: https://neo4j.com/docs/java-reference/current/tutorials-java-embedded/#tutorials-java-embedded-bolt The documentation is a bit outdated because it uses deprecated configuration. But they explain this:

The Neo4j Browser and the official Neo4j Drivers use the Bolt database protocol to communicate with Neo4j. By default, Neo4j Embedded does not expose a Bolt connector, but you can enable one. Doing so allows you to connect the services Neo4j Browser to your embedded instance.

And they make clear the correct dependency to use is:

<dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j-bolt</artifactId>
    <version>3.4.0</version>
</dependency>

Question:

I use a Neo4j java driver in my play app.

Currently I initialize a new driver for every controller (ie. for every http call). When the autoclosable close method runs it seems to block the entire call for about almost two seconds. Running without closing the drivers (obviously a bad idea) cuts my tests down from 25 seconds to 5.

I do suspect I use the driver in the wrong way and I guess I should be using one driver application wide but cannot figure out how. What is the correct way to use the java Neo4j driver in the play framework?


Answer:

The Javadoc for the Driver interface states:

Driver implementations are typically thread-safe, act as a template for Session creation and host a connection pool. All configuration and authentication settings are held immutably by the Driver. Should different settings be required, a new Driver instance should be created.

A driver maintains a connection pool for each remote Neo4j server. Therefore the most efficient way to make use of a Driver is to use the same instance across the application.

So, generally, you should use a single Driver instance.

One way to share the same instance is to implement a factory class that provides a singleton Driver instance. Here is a very basic thread-safe example:

class DriverFactory {
    private static Driver instance;
    public static synchronized Driver getDriver() {
        if (instance == null) {
            instance = GraphDatabase.driver(...);
        }
        return instance;
    }
}

Question:

How can i create multiple session for neo4j in java using this driver org.neo4j.driver.v1?

I'm able to create a single session with this instruction:

Driver driver = GraphDatabase.driver( "bolt://localhost", +

AuthTokens.basic(neo4j, password), Config.build()
            .withEncryptionLevel( Config.EncryptionLevel.REQUIRED )
            .withTrustStrategy( Config.TrustStrategy.trustOnFirstUse( new File( "/path/to/neo4j_known_hosts" ) ) )
            .toConfig() );

Answer:

In your code sample, you're not creating a Session, only a Driver.

The Session is created by calling driver.session(). If you want multiple sessions, you just call the method multiple times on the same Driver instance, e.g. if you're querying Neo4j while handling concurrent HTTP requests in your web application.

Question:

I wanted to use the neo4j-jdbc (https://github.com/neo4j-contrib/neo4j-jdbc) to connect to my Neo4j 3.0 server. I'd like to build the driver myself so that I can add it to another project as a jar file. I'm struggling to understand the readme on the official repo.

Could someone please explain how to do this, I'm hoping to clone the repo and build in Eclipse. I understand how to clone the repo it's how you go about building the driver.

Many thanks,


Answer:

As you said in the comments it seems that you want to simply connect to a Neo4j server, and as most people recommend you should use Maven or Gradle to work with your dependecies.

For that you're gonna need to create a new Maven Project:

and when you finish creating you're gonna have a project similar to this one, the one file you're looking to add this capability to connect to Neo4j is the pom.xml:

To be able to connect to Neo4j simply add this to the <dependencies></dependencies> tag:

<dependency>
  <groupId>org.neo4j</groupId>
  <artifactId>neo4j-jdbc</artifactId>
  <version>3.0</version>
</dependency>

Here's an example of a pom.xml created automaticly by a Spring Starter Project:

<?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>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Question:

Let's say I have a query to a neo4j procedure which should return 100 000 records. What I would like is a way to get my records by batches of 1000. I don't want to wait for the 100 000 records to be all sent by Neo4j, I would like to control on client side the number of records I receive. I have noticed there is a CompletionStage<Record> nextAsync() method in ResultCursor, which is doing what I want, but only one record by one. This is not optimal, as it would need too many round trips between the client and neo4j to get all the records. Is there a way to ask for the next N records ?

I am using neo4j java driver 4.0.0 in async mode.


Answer:

[UPDATED]

In neo4j 4.0+, the nextAsync() method internally gets the records in batches for you.

Its implementation returns each record from a queue that is asynchronously replenished, in batches, whenever the queue size falls below a low watermark.

So, the nextAsync() method is pretty optimal and should normally get the next record very quickly from the queue.

Question:

So far, I have been using this code to connect to embedded Neo4J instance:

DatabaseManagementService managementService = new DatabaseManagementServiceBuilder(new File("neo")).build();
GraphDatabaseService graphDb = managementService.database(DEFAULT_DATABASE_NAME);

(using this)

Now, I'm switching to Neo4J driver. But I don't know how to make the connection to embedded database. I tried this:

Driver driver = GraphDatabase.driver("bolt://localhost:7687");

but obviously is not working because there is no Neo4J server running, but just a database file. I guess I need to run bolt server first, exposing neo dir, that is where my database resides. How can I do this?


Answer:

After diving into the code, I found out that this code:

DatabaseManagementService managementService = new DatabaseManagementServiceBuilder(new File("neo")).build();

actually starts a bolt server. So I did this:

DatabaseManagementService managementService = new DatabaseManagementServiceBuilder(new File("neo")).build();
Driver driver = GraphDatabase.driver("bolt://localhost:7687");

and everything started working.

Question:

I am currently confronted with a Neo4J problem and I don't really know where to look for the answer, as I'm calling the java driver at a low level and everything seems to check out.

The situation:

  • running Neo4J in docker (3.3), gave it 14G of memory
  • using java 8
  • it's working great with OGM, processing large amounts of data and lots of queries
  • talking to it through java, neo4j-ogm-core 3.1.0, neo4j-java-driver 1.5.2

Now, I'm restructuring my project to make use of the low-level java driver instead of the OGM driver, for performance reasons. Queries such as the following one run fine:

MATCH (s:Sentence)<-[:SENTENCE_OF]-(:Paragraph)<-[:CONTAINS]-(d:Document) WHERE id(d) = {docid} RETURN s.sentence as t
parameters = {docid=2681031}

One of the queries however hangs:

MATCH  (w0:Word) , (w0:Word)<-[:CONTAINS_WORD]-(:Sentence)-[:SENTENCE_OF]-(:Paragraph)<-[:CONTAINS]-(d:Document)  WHERE w0.originalTextLower = {wT0} AND  id(d) = {docid}  RETURN w0
parameters = {wT0=abo, docid=2681032}

If I run the same query through the web interface, the query executes fine and returns no results. If I run it through the java driver, it jacks up the cpu usage to 100% and runs itself into the ground:

#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (mmap) failed to map 875036672 bytes for committing reserved memory.
# An error report file with more information is saved as:
# /hs_err_pid378.log
OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x000000063b400000, 875036672, 0) failed; error='Cannot allocate memory' (errno=12)

I call this statement through the org.neo4j.driver.v1.Session object, as follows:

session.run(statementTemplate, parameters);

I'd already appreciate a hint as to where to look further. The query seems fine, I'm running the latest software and drivers, ... the only thing I can't check is what the driver itself is doing below the water.


Answer:

Figured out the problem: the neo4j-java-driver does not handle nested queries. I had one loop that iterated over the results of 1 query. In that loop, it used the same Session object to execute another query. OGM does not complain in that situation, but neo4j-java-driver does.

Question:

Stack: TOMEE / NEO4J 2.1.6 Community Edition

What I am doing:

  • Posting an array of JSON objects to a Java JAX-RS Web Service
  • Parsing the JSON and creating the Cypher Queries
  • Trying execute the Cypher Queries and return the result in JSON.

Problem:

To avoid Duplicate Node creation, without adding additional overheads in the application code, I am using "CREATE CONSTRAINT ON"

This is what my Cypher Looks Like

CREATE (EVENTS:Events {name:'nm_Events',value:'256',label:'lb_Events'} )  
CREATE CONSTRAINT ON (EVENTS:Events) ASSERT EVENTS.name IS UNIQUE 
CREATE (LOGOUTS:Logouts {name:'nm_Logouts',value:'4',label:'lb_Logouts'} )  
CREATE CONSTRAINT ON (LOGOUTS:Logouts) ASSERT LOGOUTS.name IS UNIQUE 
CREATE (ACCIDENTAL_CLICKS:Accidental_Clicks {name:'nm_AccidentalClicks',value:'4',label:'lb_AccidentalClicks'} )  
CREATE CONSTRAINT ON (ACCIDENTAL_CLICKS:Accidental_Clicks) ASSERT ACCIDENTAL_CLICKS.name IS UNIQUE 
CREATE (INTERACTIONS:Interactions {name:'nm_Interactions',label:'lbl_interactions'} )  
CREATE CONSTRAINT ON (INTERACTIONS:Interactions) ASSERT INTERACTIONS.name IS UNIQUE 
CREATE (BUTTONS:Buttons {name:'nm_buttons',label:'lbl_buttons'} )  
CREATE CONSTRAINT ON (BUTTONS:Buttons) ASSERT BUTTONS.name IS UNIQUE 
CREATE (GROUP_BUTTON:Group_Button {name:'nm_GroupButton',value:'54',label:'lb_GroupButton'} )  
CREATE CONSTRAINT ON (GROUP_BUTTON:Group_Button) ASSERT GROUP_BUTTON.name IS UNIQUE 
CREATE (DELETE_BUTTON:Delete_Button {name:'nm_DeleteButton',value:'454',label:'lb_DeleteButton'} )  
CREATE CONSTRAINT ON (DELETE_BUTTON:Delete_Button) ASSERT DELETE_BUTTON.name IS UNIQUE 
CREATE (LOGIN_BUTTON:Login_Button {name:'nm_LoginButton',value:'256',label:'lb_LoginButton'} )  
CREATE CONSTRAINT ON (LOGIN_BUTTON:Login_Button) ASSERT LOGIN_BUTTON.name IS UNIQUE 
CREATE UNIQUE (LOGOUTS)-[:CHILD_OF]->(EVENTS) 
CREATE UNIQUE (ACCIDENTAL_CLICKS)-[:CHILD_OF]->(EVENTS) 
CREATE UNIQUE (DELETE_BUTTON)-[:CHILD_OF]->(GROUP_BUTTON) 
CREATE UNIQUE (GROUP_BUTTON)-[:CHILD_OF]->(BUTTONS) 
CREATE UNIQUE (LOGIN_BUTTON)-[:CHILD_OF]->(BUTTONS) 
CREATE UNIQUE (BUTTONS)-[:CHILD_OF]->(INTERACTIONS)

ISSUE:

While executing in NEO4J's console it gives an error

Invalid input 'N': expected 'p/P' (line 2, column 20)
"CREATE CONSTRAINT ON (EVENTS:Events) ASSERT EVENTS.name IS UNIQUE "
                    ^

I read that you cannot execute multi-line statements in the console but same issue when using the JDBC code.

Please help.


Answer:

You cannot mix DML and DDL, create the constraints / indexes upfront and the data later.

Also in the console each is an individual statement and transaction, if you want to doe the same with JDBC, run over the list of statements in a loop an execute them individually.

Question:

I'm using neo4j-community-2.3.0-M02 and my neo4j jdbc driver 3.0, when I'm creating db connection I got exception java.lang.ClassNotFoundException: org.neo4j.jdbc.Driver

Here is the method that I used create db connection.

private void createDbConnection(){
    System.out.println("Creating neo4j db connection.");
    try {
        Class.forName("org.neo4j.jdbc.Driver");
        connection = (Connection) 
                DriverManager.getConnection("jdbc:neo4j:http:/<<ip_address>>:7474/",userName,passWord);
        System.out.println("neo4jConnection:"+connection.toString());
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

Is there any mismatching between the above libraries that I used or there any error in my method?

As requested here is full stacktrace,

java.lang.ClassNotFoundException: org.neo4j.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1858)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1709)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:195)
at com.springapp.utils.Neo4jUtil.createDbConnection(Neo4jUtil.java:38)
at com.springapp.utils.Neo4jUtil.<init>(Neo4jUtil.java:29)
at com.springapp.utils.Neo4jUtil.<init>(Neo4jUtil.java:15)
at com.springapp.utils.Neo4jUtil$Neo4jHolder.<clinit>(Neo4jUtil.java:60)
at com.springapp.utils.Neo4jUtil.getInstance(Neo4jUtil.java:64)
at com.springapp.controllers.CdrProcessController.getInstance(CdrProcessController.java:208)
at com.springapp.controllers.CdrProcessController.cdrRelationClear(CdrProcessController.java:166)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Here is my pom.xml

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springapp</groupId>
<artifactId>Adaptor</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Adaptor</name>

<properties>
    <spring.version>4.1.1.RELEASE</spring.version>
</properties>

<repositories>
    <repository>
        <id>neo4j-public</id>
        <url>http://m2.neo4j.org/content/groups/everything</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>

    <!--Jackson libs-->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-lgpl</artifactId>
        <version>1.9.5</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-lgpl</artifactId>
        <version>1.9.5</version>
    </dependency>
    <!--Redis dependencies-->
    <!--Redis 2.7.2 and spring 1.5.1 are not compatible with each other-->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.6.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <!--<version>2.6.2</version>-->
        <version>2.8.0</version>
    </dependency>
    <!---->
    <!-- New redis client for threading-->
    <dependency>
        <groupId>biz.paluch.redis</groupId>
        <artifactId>lettuce</artifactId>
        <version>3.4.2.Final</version>
    </dependency>
    <!-- -->
    <!--MySQL dependencies-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.9</version>
    </dependency>
    <!--Access xml data-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.xmlbeans</groupId>
        <artifactId>xmlbeans</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
        <groupId>stax</groupId>
        <artifactId>stax-api</artifactId>
        <version>1.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>
    <!---->

    <!--Read Json-->
    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1</version>
    </dependency>
    <!---->
    <!-- Apache htttp client-->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    <!-- -->
    <!-- Json for htttp client-->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20151123</version>
    </dependency>
    <!-- -->
    <!-- Read csv files-->
    <dependency>
        <groupId>com.opencsv</groupId>
        <artifactId>opencsv</artifactId>
        <version>3.4</version>
    </dependency>
    <!-- -->

    <!-- Neo4j Jdbc -->
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-jdbc</artifactId>
        <version>3.0</version>
    </dependency>
    <!-- For file and in-memory support, add these two as well -->
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j</artifactId>
        <version>2.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-kernel</artifactId>
        <version>2.3.2</version>
        <type>test-jar</type>
    </dependency>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-io</artifactId>
        <version>2.3.2</version>
        <type>test-jar</type>
    </dependency>
</dependencies>

<build>
    <finalName>Adaptor</finalName>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <includes>
                    <include>**/*Tests.java</include>
                </includes>
            </configuration>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <directory>src/main/webapp/WEB-INF/config</directory>
            <includes>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>


Answer:

I have removed Class.forName("org.neo4j.jdbc.Driver"); line and added following two lines before creating the connection.

Driver driver = new org.neo4j.jdbc.Driver();
DriverManager.registerDriver(driver);

I did this after referring this tutorial. Second approach solved my issue successfully.