知识库

在您的 Java 应用程序中嵌入 neo4j-enterprise

Neo4j Java 参考文档》通常描述了如何在您的 Java 应用程序中嵌入 Neo4j Community Edition。如果您拥有 Neo4j Enterprise 的许可,本文将指导您如何设置项目以在应用程序中嵌入使用 Neo4j Enterprise。

创建一个新项目

首先,您需要下载 IntelliJ Community Edition。下载完成后,创建一个新项目 (New Project)>Java>命令行应用程序 (Command Line App)。

指定其名称为 embedded 和基础包

配置 Maven 仓库

在您的主目录中创建一个名为 .m2 的文件夹

按如下方式创建 ${HOME}/.m2/settings.xml 文件。

请参考知识库 依赖位置

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                        https://maven.apache.org/xsd/settings-1.0.0.xsd">
    <servers>
        <server>
            <id>neo4j-enterprise</id>
            <username>neo4j-enterprise</username>
            <password>modify password there</password>
        </server>
    </servers>
</settings>

创建项目 pom.xml 文件

一个 Project Object Model (POM) 是 Maven 中的基本工作单元。它是一个 XML 文件,包含项目信息以及 Maven 用于构建项目的配置详情。它包含大多数项目的默认值。

使用 IntelliJ 在项目根目录创建一个新的文本文件,命名为 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!-- maven specific -->
    <modelVersion>4.0.0</modelVersion>
    <artifactId>embedded</artifactId>

    <!-- your own project settings-->
    <groupId>com.example</groupId>
    <version>1.0-snapshot</version>
    <name>embedded</name>
    <description>Embedded demo project</description>

    <!-- Where to download the artifact-->
    <repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>neo4j-enterprise</id>
            <name>Neo4j Enterprise Artifacts</name>
            <url>http://m2.neo4j.com/enterprise</url>
        </repository>
    </repositories>

    <!-- Which artifact is required-->
    <dependencies>

        <dependency>
            <groupId>com.neo4j</groupId>
            <!-- com.neo4j for enterprise, doc needs to be fixed: https://neo4j.ac.cn/docs/java-reference/3.5/tutorials-java-embedded/#editions -->
            <artifactId>neo4j-enterprise</artifactId>
            <version>3.5.3</version>
        </dependency>
    </dependencies>

    <!-- to specify which version of java to compile the source code, here: java 11-->
    <build>
        <defaultGoal>install</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>11</source> <!-- source code version -->
                    <target>11</target> <!-- binary destination version -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

创建 Java 类

在 IntelliJ 中,右键单击 src,选择 New > Java Class,并将其命名为 EmbeddedNeo4j。您可以粘贴以下代码,或者参考 Java 参考手册 中的指导。

/*
 * Licensed to Neo4j under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Neo4j licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://apache.ac.cn/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.File;
import java.io.IOException;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.EnterpriseGraphDatabaseFactory;
import org.neo4j.io.fs.FileUtils;

public class EmbeddedNeo4j
{
    private static final File databaseDirectory = new File( "/Users/jphoulchand/neo4j/test/embedded-neo4j-enterprise/" );

    public String greeting;

    // tag::vars[]
    GraphDatabaseService graphDb;
    Node firstNode;
    Node secondNode;
    Relationship relationship;
    // end::vars[]

    // tag::createReltype[]
    private enum RelTypes implements RelationshipType
    {
        KNOWS
    }
    // end::createReltype[]

    public static void main( final String[] args ) throws IOException
    {
        EmbeddedNeo4j hello = new EmbeddedNeo4j();
        hello.createDb();
        hello.removeData();
        hello.shutDown();
    }

    void createDb() throws IOException
    {
        FileUtils.deleteRecursively( databaseDirectory );

        // tag::startDb[]
        graphDb = new EnterpriseGraphDatabaseFactory().newEmbeddedDatabase( databaseDirectory );
        registerShutdownHook( graphDb );
        // end::startDb[]

        // tag::transaction[]
        try ( Transaction tx = graphDb.beginTx() )
        {
            // Database operations go here
            // end::transaction[]
            // tag::addData[]
            firstNode = graphDb.createNode();
            firstNode.setProperty( "message", "Hello, " );
            secondNode = graphDb.createNode();
            secondNode.setProperty( "message", "World!" );

            relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
            relationship.setProperty( "message", "brave Neo4j " );
            // end::addData[]

            // tag::readData[]
            System.out.print( firstNode.getProperty( "message" ) );
            System.out.print( relationship.getProperty( "message" ) );
            System.out.print( secondNode.getProperty( "message" ) );
            // end::readData[]

            greeting = ( (String) firstNode.getProperty( "message" ) )
                    + ( (String) relationship.getProperty( "message" ) )
                    + ( (String) secondNode.getProperty( "message" ) );

            // tag::transaction[]
            tx.success();
        }
        // end::transaction[]
    }

    void removeData()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            // tag::removingData[]
            // let's remove the data
            firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
            firstNode.delete();
            secondNode.delete();
            // end::removingData[]

            tx.success();
        }
    }

    void shutDown()
    {
        System.out.println();
        System.out.println( "Shutting down database ..." );
        // tag::shutdownServer[]
        graphDb.shutdown();
        // end::shutdownServer[]
    }

    // tag::shutdownHook[]
    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 application).
        Runtime.getRuntime().addShutdownHook( new Thread()
        {
            @Override
            public void run()
            {
                graphDb.shutdown();
            }
        } );
    }
    // end::shutdownHook[]
}
© . All rights reserved.