Neo4j 提供 JAVA API 以编程方式执行所有数据库操作。它支持三种类型的API:

1、Neo4j 原生的 Java API

原生 Java API 是一种低级别的纯 JAVA API,用于执行数据库操作。

2、Neo4j Cypher Java API

Cypher Java API 是简单而强大的 JAVA API,用于执行所有CQL命令以执行数据库操作。

3、Neo4j OGM JAVA API

OGM Java API和Mybatis、JPA类似可以直接和SpringData整合

 

Neo4j 原生的 Java API

import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;

import java.io.File;

public class Neo4jNativeJavaAPI {
    private static void registerShutdownHook(final GraphDatabaseService graphDB) {
        // Registers a shutdown hook for the Neo4j instance so that it shuts down nicely
        // when the VM exits (even if you "Ctrl-C" the running example before it's completed)
        /*为了确保neo4j数据库的正确关闭,我们可以添加一个关闭钩子方法 registerShutdownHook。
         *这个方法的意思就是在jvm中增加一个关闭的钩子,
         *当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,
         *当系统执行完这些钩子后,jvm才会关闭。
         *所以这些钩子可以在jvm关闭的时候进行内存清理、对象销毁等操作。*/
        Runtime.getRuntime().addShutdownHook(
                new Thread() {
                    public void run() {
                        //Shutdown the Database
                        System.out.println("Server is shutting down");
                        graphDB.shutdown();
                    }
                }
        );
    }

    public static void main(String[] args) {
        //指定 Neo4j 存储路径
        File file = new File("D:\\neo4j-community-3.2.6\\data\\databases\\graph.db");
        //Create a new Object of Graph Database
        GraphDatabaseService graphDB = new GraphDatabaseFactory().newEmbeddedDatabase(file);
        System.out.println("Server is up and Running");
        try(Transaction tx = graphDB.beginTx()){
            /**
             * 新增User节点
             * 添加Lable以区分节点类型
             * 每个节点设置name属性
             */
            Node user1 = graphDB.createNode(MyLabels.USERS);
            user1.setProperty("name", "John Johnson");

            Node user2 = graphDB.createNode(MyLabels.USERS);
            user2.setProperty("name", "Kate Smith");

            Node user3 = graphDB.createNode(MyLabels.USERS);
            user3.setProperty("name", "Jack Jeffries");
            /**
             * 为user1添加Friend关系
             * 注:Neo4j的关系是有向的箭头,正常来讲Friend关系应该是双向的,
             * 此处为了简单起见,将关系定义成单向的,不会影响后期的查询
             */
            user1.createRelationshipTo(user2,MyRelationshipTypes.IS_FRIEND_OF);
            user1.createRelationshipTo(user3,MyRelationshipTypes.IS_FRIEND_OF);
            /**
             * 新增Movie节点
             * 添加Lable以区分节点类型
             * 每个节点设置name属性
             */
            Node movie1 = graphDB.createNode(MyLabels.MOVIES);
            movie1.setProperty("name", "Fargo");

            Node movie2 = graphDB.createNode(MyLabels.MOVIES);
            movie2.setProperty("name", "Alien");

            Node movie3 = graphDB.createNode(MyLabels.MOVIES);
            movie3.setProperty("name", "Heat");
            /**
             * 为User节点和Movie节点之间添加HAS_SEEN关系, HAS_SEEN关系设置stars属性
             */
            Relationship relationship1 = user1.createRelationshipTo(movie1, MyRelationshipTypes.HAS_SEEN);
            relationship1.setProperty("stars", 5);
            Relationship relationship2 = user2.createRelationshipTo(movie3, MyRelationshipTypes.HAS_SEEN);
            relationship2.setProperty("stars", 3);
            Relationship relationship6 = user2.createRelationshipTo(movie2, MyRelationshipTypes.HAS_SEEN);
            relationship6.setProperty("stars", 6);
            Relationship relationship3 = user3.createRelationshipTo(movie1, MyRelationshipTypes.HAS_SEEN);
            relationship3.setProperty("stars", 4);
            Relationship relationship4 = user3.createRelationshipTo(movie2, MyRelationshipTypes.HAS_SEEN);
            relationship4.setProperty("stars", 5);

            tx.success();
            System.out.println("Done successfully");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            graphDB.shutdown();    //关闭数据库
        }

        //Register a Shutdown Hook
        registerShutdownHook(graphDB);
    }
}

/**
 * Label类型枚举类
 */
enum MyLabels implements Label {
    MOVIES, USERS
}

/**
 * 关系类型枚举类
 */
enum MyRelationshipTypes implements RelationshipType {
    IS_FRIEND_OF, HAS_SEEN
}

Neo4j Cypher Java API

import com.dataqin.util.JdbcUtil;
import org.junit.Test;
import org.neo4j.driver.v1.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import static org.neo4j.driver.v1.Values.parameters;


public class TestNeo4jJavaDriver {


    /**
     * 读取配置文件信息
     *
     * @return
     */
    private static Properties getProperties() {
        Properties properties = new Properties();
        try {
            InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("application.properties");
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }


    private Driver createDrive() throws Exception {

        String uri = null;
        String username = null;
        String password = null;
        try {
            uri = getProperties().get("spring.data.neo4j.uri").toString();
            username = getProperties().get("spring.data.neo4j.username").toString();
            password = getProperties().get("spring.data.neo4j.password").toString();
        } catch (Exception e) {
            throw new Exception("读取neo4j配置文件时出错");
        }

        return GraphDatabase.driver(uri, AuthTokens.basic(username, password));
    }

    @Test
    public void tesQueryCount() throws Exception {

        Driver driver = createDrive();
        Session session = driver.session();

        StatementResult result = session.run("match (x:TableNode)  where x.tableName={tableName} and x.dataBase={dataBase}  return  count(x) as count",
                parameters("dataBase", "test", "tableName", "tableName1"));

        while (result.hasNext()) {
            Record record = result.next();
            System.out.println(record.get("count").asInt());
        }

        session.close();
        driver.close();
    }

    @Test
    public void tesAddNodes() throws Exception {

        Driver driver = createDrive();
        try(Session session = driver.session()){
            try(Transaction tx = session.beginTransaction()){
                tx.run("create(n:TableNode{dataBase:{dataBase},tableName:{tableName}})",
                        parameters("dataBase","test","tableName","rootTable"));
                tx.run("create(n:TableNode{dataBase:{dataBase},tableName:{tableName}})",
                        parameters("dataBase","test","tableName","tablename1"));
                tx.run("create(n:TableNode{dataBase:{dataBase},tableName:{tableName}})",
                        parameters("dataBase","test","tableName","tablename2"));


                tx.run("create(n:ColumnRsNode{fromDataBase:{fromDataBase},toDataBase:{toDataBase},fromKey:{fromKey},toKey:{toKey}" +
                                ",fromTable:{fromTable},toTable:{toTable}})",
                        parameters("fromDataBase","test","toDataBase","test", "fromKey","tablename1.key1","toKey", "rootTable.key1","fromTable", "tablename1","toTable", "rootTable"));
                tx.run("create(n:ColumnRsNode{fromDataBase:{fromDataBase},toDataBase:{toDataBase},fromKey:{fromKey},toKey:{toKey}" +
                                ",fromTable:{fromTable},toTable:{toTable}})",
                        parameters("fromDataBase","test","toDataBase","test", "fromKey","tablename1.key2","toKey", "rootTable.key1","fromTable", "tablename1","toTable", "rootTable"));

                tx.run("create(n:ColumnRsNode{fromDataBase:{fromDataBase},toDataBase:{toDataBase},fromKey:{fromKey},toKey:{toKey}" +
                                ",fromTable:{fromTable},toTable:{toTable}})",
                        parameters("fromDataBase","test","toDataBase","test", "fromKey","tablename2.key1","toKey", "tablename1.key1","fromTable", "tablename2","toTable", "tablename1"));

                tx.success();
            }

        }
        driver.close();

    }

    @Test
    public void tesAddRlation() throws Exception {

        Driver driver = createDrive();
        Session session = driver.session();

        String dataBase = "test";
        String tableName = "rootTable";

        StatementResult result = session.run("match (x:TableNode)  where x.tableName={tableName} and x.dataBase={dataBase} return x",
                parameters("dataBase", dataBase, "tableName", tableName));

        TableNode tableNode = new TableNode();
        while (result.hasNext()) {
            Record record = result.next();
            Value x = record.get("x");
            tableNode.setId(x.asNode().id());
            tableNode.setDataBase(x.get("dataBase").asString());
            tableNode.setTableName(x.get("tableName").asString());
        }


        result = session.run("match (x:ColumnRsNode)  where x.fromTable={tableName} and x.fromDataBase={dataBase} return x",
                parameters("dataBase", dataBase, "tableName", tableName));

        while (result.hasNext()) {

            Record record = result.next();
            Value x = record.get("x");

            ColumnRsNode columnRsNode = new ColumnRsNode();
            columnRsNode.setId(x.asNode().id());
            columnRsNode.setFromDataBase(x.get("fromDataBase").asString());
            columnRsNode.setFromKey(x.get("fromKey").asString());
            columnRsNode.setFromTable(x.get("fromTable").asString());
            columnRsNode.setName(x.get("name").asString());
            columnRsNode.setToDataBase(x.get("toDataBase").asString());
            columnRsNode.setToKey(x.get("toKey").asString());
            columnRsNode.setToTable(x.get("toTable").asString());

            int count = 0;
            result = session.run("MATCH (a:TableNode),(b:ColumnRsNode),p=(a)-[]-(b) where id(a)={tableNodeId} and id(b)={columnRsNodeId} return count(p) as count",
                    parameters("tableNodeId", tableNode.getId(), "columnRsNodeId", columnRsNode.getId()));

            while (result.hasNext()) {
                record = result.next();
                count = record.get("count").asInt();
            }
            if (count == 0) {
                session.run("MATCH (a:TableNode), (b:ColumnRsNode) " +
                        "WHERE ID(a) = " + tableNode.getId() + " AND ID(b) = " + columnRsNode.getId()
                        + " CREATE (a)-[:blood]->(b)");
            }
        }


        result = session.run("match (x:ColumnRsNode)  where x.toTable={tableName} and x.toDataBase={dataBase} return x",
                parameters("dataBase", dataBase, "tableName", tableName));

        while (result.hasNext()) {
            Record record = result.next();
            Value x = record.get("x");

            ColumnRsNode columnRsNode = new ColumnRsNode();
            columnRsNode.setId(x.asNode().id());
            columnRsNode.setFromDataBase(x.get("fromDataBase").asString());
            columnRsNode.setFromKey(x.get("fromKey").asString());
            columnRsNode.setFromTable(x.get("fromTable").asString());
            columnRsNode.setName(x.get("name").asString());
            columnRsNode.setToDataBase(x.get("toDataBase").asString());
            columnRsNode.setToKey(x.get("toKey").asString());
            columnRsNode.setToTable(x.get("toTable").asString());


            result = session.run("MATCH (a:TableNode),(b:ColumnRsNode),p=(a)-[]-(b) where id(a)={tableNodeId} and id(b)={columnRsNodeId} return count(p) as count",
                    parameters("tableNodeId", tableNode.getId(), "columnRsNodeId", columnRsNode.getId()));

            int count = 0;
            while (result.hasNext()) {
                record = result.next();
                count = record.get("count").asInt();
            }
            if (count == 0) {
                session.run("MATCH (a:TableNode), (b:ColumnRsNode) " +
                        "WHERE ID(a) = " + tableNode.getId() + " AND ID(b) = " + columnRsNode.getId()
                        + " CREATE (a)-[:blood]->(b)");
            }

        }


        session.close();
        driver.close();


    }


}

Neo4j OGM JAVA API

import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.ogm.config.ClasspathConfigurationSource;
import org.neo4j.ogm.config.Configuration;
import org.neo4j.ogm.config.ConfigurationSource;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;

import java.io.IOException;
import java.io.Reader;
import java.util.*;

public class TestCollectBlood {


    private Session neo4jSession;

 

    @Before
    public void init() throws IOException {
 
        ConfigurationSource configurationSource = new ClasspathConfigurationSource("application.properties");

        Properties properties = configurationSource.properties();

        String uri = properties.get("spring.data.neo4j.uri") == null ? null : properties.get("spring.data.neo4j.uri").toString();
        String username = properties.get("spring.data.neo4j.username") == null ? null : properties.get("spring.data.neo4j.username").toString();
        String password = properties.get("spring.data.neo4j.password") == null ? null : properties.get("spring.data.neo4j.password").toString();

        Configuration config = new Configuration.Builder()
                .uri(uri)
                .credentials(username, password)
                .build();
        SessionFactory sessionFactory = new SessionFactory(config, "com.dataqin.dataobject.po");
        neo4jSession = sessionFactory.openSession();

 
    }


 
    @Test
    public void Test() throws Exception {

        try {
            
            neo4jSession.beginTransaction();

            Map param = new HashMap<String, String>();
                             
            param.put("dataBase", "fromDataBase");
            param.put("tableName", "fromTable");
            String countHql = "match (x:TableNode)  where x.tableName={tableName} and x.dataBase={dataBase}  return  count(x) as count";
            
            Integer count = neo4jSession.queryForObject(Integer.class, countHql, param);
            if (count == 0) {
                   TableNode fromTableNode = new TableNode( "fromDataBase", "fromTable");
                   neo4jSession.save(fromTableNode);

            }
  
            neo4jSession.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
            neo4jSession.getTransaction().rollback();
        } finally {
            sqlSession.close();
        }

    }
     
}