Eclipse下maven使用嵌入式(Embedded)Neo4j创建Hello World项目

简介: Eclipse下maven使用嵌入式(Embedded)Neo4j创建Hello World项目新建一个maven工程,这里不赘述如何新建maven工程。添加Neo4j jar到你的工程有两种方式:上网站官网下载jar包,根据自己的系统下载不同的压缩包,详细过程不描述,请自行搜索其他博客通过maven获得jar包pom.

Eclipse下maven使用嵌入式(Embedded)Neo4j创建Hello World项目

新建一个maven工程,这里不赘述如何新建maven工程。

添加Neo4j jar到你的工程

有两种方式:

  • 上网站官网下载jar包,根据自己的系统下载不同的压缩包,详细过程不描述,请自行搜索其他博客
  • 通过maven获得jar包

pom.xml文件下添加dependency

<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>nd.esp.com</groupId>
  <artifactId>MyNeo4j</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MyNeo4j</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

<!-- Embedded Neo4j依赖,目前最新版本是2.3.3-->
  <dependencies>
    <dependency>
     <groupId>org.neo4j</groupId>
     <artifactId>neo4j-slf4j</artifactId>
     <version>2.3.3</version>
    </dependency>
  </dependencies>
</project>

Hello World 程序

代码可以在github上看到:https://github.com/neo4j/neo4j/blob/2.3.3/community/embedded-examples/src/main/java/org/neo4j/examples/EmbeddedNeo4j.java

/*
 * Licensed to Neo Technology under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Neo Technology 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
 *
 * http://www.apache.org/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.
 */
package org.neo4j.examples;

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.GraphDatabaseFactory;
import org.neo4j.io.fs.FileUtils;

public class EmbeddedNeo4j
{
    // Embedded Neo4j会在本地产生一个文件夹(类似于Mysql的数据库)
    private static final String DB_PATH = "target/neo4j-hello-db";

    public String greeting;

    // START SNIPPET: vars
    GraphDatabaseService graphDb;
    Node firstNode;
    Node secondNode;
    Relationship relationship;
    // END SNIPPET: vars

    // START SNIPPET: createReltype
    private static enum RelTypes implements RelationshipType
    {
        KNOWS
    }
    // END SNIPPET: 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( new File( DB_PATH ) );

        // START SNIPPET: startDb
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
        registerShutdownHook( graphDb );
        // END SNIPPET: startDb

        // START SNIPPET: transaction
        // Embedded Neo4j基本上所有的操作都需要在事务内执行
        try ( Transaction tx = graphDb.beginTx() )
        {
            // Database operations go here
            // END SNIPPET: transaction
            // START SNIPPET: 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 SNIPPET: addData

            // START SNIPPET: readData
            System.out.print( firstNode.getProperty( "message" ) );
            System.out.print( relationship.getProperty( "message" ) );
            System.out.print( secondNode.getProperty( "message" ) );
            // END SNIPPET: readData

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

            // START SNIPPET: transaction
            tx.success();
        }
        // END SNIPPET: transaction
    }
    // 移除新建的数据
    void removeData()
    {
        try ( Transaction tx = graphDb.beginTx() )
        {
            // START SNIPPET: removingData
            // let's remove the data
            firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
            firstNode.delete();
            secondNode.delete();
            // END SNIPPET: removingData

            tx.success();
        }
    }
    // 关闭Neo4j 数据库
    void shutDown()
    {
        System.out.println();
        System.out.println( "Shutting down database ..." );
        // START SNIPPET: shutdownServer
        graphDb.shutdown();
        // END SNIPPET: shutdownServer
    }

    // 为Neo4j 实例注册一个关闭的hook,当VM被强制退出时,Neo4j 实例能够正常关闭
    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();
            }
        } );
    }
}

在事务中操作

所有的操作都必须在一个事务中完成。这是官方一个刻意的设计,因为他们坚信事务划分是企业型数据库重要的一部分。所以,你可以使用如下的方式开启事务:
try ( Transaction tx = graphDb.beginTx() ){
// Database operations go here
tx.success();
}

try(){}这种语法是在jdk1.7之后支持的,这种方式能够让vm支持自动释放使用结束的资源。在这里可以不需要自己调用语句:
finally{
tx.close();
}

如果你使用低于jdk1.7以后的版本,可以修改为如下的代码:
Transaction tx = graphDb.beginTx()
try{
// Database operations go here
tx.success();
}finally{
tx.close();
}

创建一个简单的图

使用一下代码创建两个节点和一个关系:

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 " );

创建之后的图数据如下:
HelloWorld输出结果

本文翻译自官网使用手册:http://neo4j.com/docs/stable/tutorials-java-embedded-hello-world.html

教程结束,感谢阅读。

欢迎转载,但请注明本文链接,谢谢。
2016/4/5 20:09:25

目录
相关文章
|
2月前
|
Java Maven
手把手教你搭建Maven项目
手把手教你搭建Maven项目
31 0
|
3月前
|
Java Maven
java修改当前项目的maven仓库地址为国内
修改当前项目的maven仓库地址为国内
|
4月前
|
Dubbo Java 应用服务中间件
微服务框架(十)Maven Archetype制作Dubbo项目原型
  此系列文章将会描述Java框架Spring Boot、服务治理框架Dubbo、应用容器引擎Docker,及使用Spring Boot集成Dubbo、Mybatis等开源框架,其中穿插着Spring Boot中日志切面等技术的实现,然后通过gitlab-CI以持续集成为Docker镜像。   本文为Maven Archetype的制作及使用,使用archetype插件制作Dubbo项目原型
|
2月前
|
XML Java Maven
【Maven技术专题】「实战开发系列」盘点Maven项目中打包需要注意到的那点事儿
【Maven技术专题】「实战开发系列」盘点Maven项目中打包需要注意到的那点事儿
37 0
|
5天前
|
Java Maven
idea中maven项目pom文件Could not acquire lock(s)
idea中maven项目pom文件Could not acquire lock(s)
|
24天前
|
Java Maven Spring
【操作宝典】IntelliJ IDEA新建maven项目详细教程
【操作宝典】IntelliJ IDEA新建maven项目详细教程
33 1
|
2月前
|
Java Maven 开发工具
maven导入项目出现Unable to import maven project: See logs for details
maven导入项目出现Unable to import maven project: See logs for details
11 0
maven导入项目出现Unable to import maven project: See logs for details
|
1天前
|
Java Scala Maven
Maven 项目模板
Maven的`archetype`用于创建定制项目结构,即项目模板。通过`mvn archetype:generate`命令能快速生成如Java应用的项目。在命令行中执行该命令后,会列出多个远程模板选项供选择。用户可输入数字或应用过滤器,按Enter选择默认(203:maven-archetype-quickstart)来创建简单Java应用程序。
|
2天前
|
XML Java 测试技术
Maven 构建 & 项目测试
该文介绍了如何使用Maven进行Java应用的构建与测试。在`C:/MVN/consumerBanking`项目中,`pom.xml`配置了JUnit依赖。Maven默认创建了源码和测试文件,通过命令`mvn clean package`进行构建,生成`consumerBanking-1.0-SNAPSHOT.jar`。测试报告在`surefire-reports`文件夹。新增`Util`类并更新`App`后,执行`mvn clean compile`编译,然后运行`java -cp . com.companyname.bank.App`显示&quot;Hello World!&quot;。
|
2天前
|
Java Maven
Maven 构建 Java 项目
使用Maven的`maven-archetype-quickstart`插件在C:\MVN下创建Java应用,命令包括`groupId`, `artifactId`, 和 `archetypeArtifactId`参数。生成的项目包含src/main/java和src/test/java目录,分别用于存放源代码和测试代码,还有src/main/resources用于资源文件。默认提供App.java主类和AppTest.java测试类。按照预设结构组织文件,Maven将自动管理构建过程。

热门文章

最新文章

推荐镜像

更多