# 用Neo4j訪問數據
本指南將引導您完成使用 的過程, [Spring Data Neo4j](https://projects.spring.io/spring-data-neo4j/) 來構建應用程序 該應用程序將數據存儲在 中并從中檢索 [Neo4j](https://www.neo4j.com/) 基于圖形的數據庫 數據。
## 你會建立什么
您將使用Neo4j的 [NoSQL](https://wikipedia.org/wiki/NoSQL) 基于 圖的數據存儲來構建嵌入式Neo4j服務器,存儲實體和關系以及開發查詢。
## 你需要什么
* 約15分鐘
* 最喜歡的文本編輯器或IDE
* [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本
* [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi)
* 您還可以將代碼直接導入到IDE中:
* [彈簧工具套件(STS)](https://spring.io/guides/gs/sts)
* [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)
## 如何完成本指南
像大多數Spring 一樣 [入門指南](https://spring.io/guides) ,您可以從頭開始并完成每個步驟,也可以繞過您已經熟悉的基本設置步驟。 無論哪種方式,您最終都可以使用代碼。
要 **從頭開始** ,請繼續進行“ [從Spring Initializr開始”](https://spring.io/guides/gs/accessing-data-neo4j/#scratch) 。
要 **跳過基礎知識** ,請執行以下操作:
* [下載](https://github.com/spring-guides/gs-accessing-data-neo4j/archive/master.zip) 并解壓縮本指南的源存儲庫,或使用 對其進行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-accessing-data-neo4j.git](https://github.com/spring-guides/gs-accessing-data-neo4j.git)`
* 光盤進入 `gs-accessing-data-neo4j/initial`
* 繼續 [定義一個簡單實體](https://spring.io/guides/gs/accessing-data-neo4j/#initial) 。
**完成后** ,您可以根據中的代碼檢查結果 `gs-accessing-data-neo4j/complete`.
## 從Spring Initializr開始
如果使用Maven,請訪問 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=accessing-data-neo4j&name=accessing-data-neo4j&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.accessing-data-neo4j&dependencies=data-neo4j) 以生成具有所需依賴項的新項目(Spring Data Neo4j)。
以下清單顯示了 `pom.xml` 選擇Maven時創建的文件:
~~~
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>accessing-data-neo4j</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>accessing-data-neo4j</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</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>
</project>
~~~
如果使用Gradle,請訪問 [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=accessing-data-neo4j&name=accessing-data-neo4j&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.accessing-data-neo4j&dependencies=data-neo4j) 以生成具有所需依賴項的新項目(Spring Data Neo4j)。
以下清單顯示了 `build.gradle`選擇Gradle時創建的文件:
~~~
plugins {
id 'org.springframework.boot' version '2.4.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-neo4j'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
~~~
配置該項??目以適合本教程中的示例。
### 手動初始化(可選)
如果要手動初始化項目而不是使用前面顯示的鏈接,請按照以下步驟操作:
1. 導航到 [https://start.spring.io](https://start.spring.io) 。 該服務提取應用程序所需的所有依賴關系,并為您完成大部分設置。
2. 選擇Gradle或Maven以及您要使用的語言。 本指南假定您選擇了Java。
3. 單擊 **Dependencies,** 然后選擇 **Spring Data Neo4j** 。
4. 點擊 **生成** 。
5. 下載生成的ZIP文件,該文件是使用您的選擇配置的Web應用程序的存檔。
如果您的IDE集成了Spring Initializr,則可以從IDE中完成此過程。
## Standing up a Neo4j Server
Before you can build this application, you need to set up a Neo4j server.
Neo4j has an open source server you can install for free.
在安裝了Homebrew的Mac上,運行以下命令:
~~~
$ brew install neo4j
~~~
有關其他選項,請訪問 [https://neo4j.com/download/community-edition/](https://neo4j.com/download/community-edition/) 。
安裝后,通過運行以下命令以默認設置啟動它:
~~~
$ neo4j start
~~~
您應該看到類似于以下內容的輸出:
~~~
Starting Neo4j.
Started neo4j (pid 96416). By default, it is available at http://localhost:7474/
There may be a short delay until the server is ready.
See /usr/local/Cellar/neo4j/3.0.6/libexec/logs/neo4j.log for current status.
~~~
默認情況下,Neo4j的用戶名和密碼為 `neo4j` 和 `neo4j`。 但是,它要求更改新的帳戶密碼。 為此,請運行以下命令:
~~~
curl -v -u neo4j:neo4j POST localhost:7474/user/neo4j/password -H "Content-type:application/json" -d "{\"password\":\"secret\"}"
~~~
這會將密碼從 `neo4j` 到 `secret`\-生產中不得做的事! 完成該步驟后,您應該準備運行本指南的其余部分。
## 定義一個簡單實體
Neo4j捕獲實體及其關系,這兩個方面都具有同等重要的意義。 想象一下,您正在對一個系統建模,在該系統中存儲每個人的記錄。 但是,您還想跟蹤某人的同事( `teammates`在此示例中)。 借助Spring Data Neo4j,您可以使用一些簡單的注釋捕獲所有內容,如下面的清單(在 `src/main/java/com/example/accessingdataneo4j/Person.java`)顯示:
~~~
package com.example.accessingdataneo4j;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.data.neo4j.core.schema.Id;
import org.springframework.data.neo4j.core.schema.Node;
import org.springframework.data.neo4j.core.schema.Property;
import org.springframework.data.neo4j.core.schema.Relationship;
import org.springframework.data.neo4j.core.schema.GeneratedValue;
@Node
public class Person {
@Id @GeneratedValue private Long id;
private String name;
private Person() {
// Empty constructor required as of Neo4j API 2.0.5
};
public Person(String name) {
this.name = name;
}
/**
* Neo4j doesn't REALLY have bi-directional relationships. It just means when querying
* to ignore the direction of the relationship.
* https://dzone.com/articles/modelling-data-neo4j
*/
@Relationship(type = "TEAMMATE")
public Set<Person> teammates;
public void worksWith(Person person) {
if (teammates == null) {
teammates = new HashSet<>();
}
teammates.add(person);
}
public String toString() {
return this.name + "'s teammates => "
+ Optional.ofNullable(this.teammates).orElse(
Collections.emptySet()).stream()
.map(Person::getName)
.collect(Collectors.toList());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
~~~
在這里你有一個 `Person` 僅具有一個屬性的類: `name`.
The `Person` class is annotated with `@NodeEntity`. When Neo4j stores it, a new node is created. This class also has an `id` marked `@GraphId`. Neo4j uses `@GraphId` internally to track the data.
下一個重要的部分是 `teammates`。 很簡單 `Set<Person>` 但被標記為 `@Relationship`。 這意味著該集合的每個成員也應作為單獨的成員存在 `Person`節點。 注意方向如何設置為 `UNDIRECTED`。 這意味著當您查詢 `TEAMMATE` 關系,Spring Data Neo4j忽略了關系的方向。
隨著 `worksWith()` 方法,您可以輕松地將人們聯系在一起。
最后,您有一個方便的地方 `toString()` 打印此人的姓名和該人的同事的方法。
## 創建簡單查詢
Spring Data Neo4j專注于在Neo4j中存儲數據。 但是它繼承了Spring Data Commons項目的功能,包括導出查詢的功能。 本質上,您無需學習Neo4j的查詢語言。 相反,您可以編寫一些方法,然后為您編寫查詢。
要查看其工作原理,請創建一個查詢接口 `Person`節點。 以下清單(在 `src/main/java/com/example/accessingdataneo4j/PersonRepository.java`)顯示了這樣的查詢:
~~~
package com.example.accessingdataneo4j;
import java.util.List;
import org.springframework.data.neo4j.repository.Neo4jRepository;
public interface PersonRepository extends Neo4jRepository<Person, Long> {
Person findByName(String name);
List<Person> findByTeammatesName(String name);
}
~~~
`PersonRepository` 擴展 `Neo4jRepository` 接口并插入其操作的類型: `Person`。 此接口包含許多操作,包括標準的CRUD(創建,讀取,更新和刪除)操作。
但是您可以通過聲明其他方法的簽名來定義其他查詢。 在這種情況下,您添加了 `findByName`,它尋找類型的節點 `Person` 并找到與之匹配的 `name`。 你也有 `findByTeammatesName`,它尋找一個 `Person` 節點,深入到 `teammates` 字段,并根據隊友的比賽 `name`.
## 訪問Neo4j的權限
Neo4j Community Edition需要憑據才能訪問它。 您可以通過設置幾個屬性(在 `src/main/resources/application.properties`),如以下清單所示:
~~~
spring.neo4j.uri=bolt://localhost:7687
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=secret
~~~
這包括默認的用戶名( `neo4j`)以及我們之前選擇的新設置的密碼( `secret`).
不要在源存儲庫中存儲真實憑證。 而是在您的運行時中使用 配置它們 Spring Boot的屬性overrides 。
將其放置到位后,您可以將其連接起來,看看它是什么樣子!
## 創建一個應用程序類
Spring Initializr為應用程序創建一個簡單的類。 以下清單顯示了Initializr為此示例創建的類(在 `src/main/java/com/example/accessingdataneo4j/AccessingDataNeo4jApplication.java`):
~~~
package com.example.accessingdataneo4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AccessingDataNeo4jApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataNeo4jApplication.class, args);
}
}
~~~
`@SpringBootApplication` 是一個方便注釋,它添加了以下所有內容:
* `@Configuration`:將類標記為應用程序上下文的Bean定義的源。
* `@EnableAutoConfiguration`:告訴Spring Boot根據類路徑設置,其他bean和各種屬性設置開始添加bean。 例如,如果 `spring-webmvc` 在類路徑上,此注釋將應用程序標記為Web應用程序并激活關鍵行為,例如設置 `DispatcherServlet`.
* `@ComponentScan`:告訴Spring在服務器中尋找其他組件,配置和服務 `com/example` 包,讓它找到控制器。
這 `main()` 方法使用Spring Boot的 `SpringApplication.run()`啟動應用程序的方法。 您是否注意到沒有一行XML? 沒有 `web.xml`文件。 該Web應用程序是100%純Java,因此您無需處理任何管道或基礎結構。
只要它們包含在您的同一軟件包(或子軟件包)中,Spring Boot就會自動處理這些存儲庫 `@SpringBootApplication`班級。 為了更好地控制注冊過程,您可以使用 `@EnableNeo4jRepositories` 注解。
默認, @EnableNeo4jRepositories在當前包中掃描任何擴展了Spring Data存儲庫接口之一的接口。 你可以用它 basePackageClasses=MyRepository.class 如果您的項目布局中有多個項目并且找不到存儲庫,則可以安全地告訴Spring Data Neo4j按類型掃描其他根包。
顯示日志記錄輸出。 該服務應在幾秒鐘內啟動并運行。
現在自動連線的實例 `PersonRepository`您之前定義的。 Spring Data Neo4j動態地實現該接口,并插入所需的查詢代碼以滿足接口的義務。
這 `main` 方法使用Spring Boot的 `SpringApplication.run()` 啟動應用程序并調用 `CommandLineRunner` 建立關系。
在這種情況下,您將創建三個本地 `Person`實例:格雷格(Greg),羅伊(Roy)和克雷格(Craig)。 最初,它們僅存在于內存中。 請注意,還沒有人是任何人的隊友。
首先,您會找到Greg,指出他與Roy和Craig合作,然后再次堅持下去。 記住,隊友關系被標記為 `UNDIRECTED`(即雙向)。 這意味著Roy和Craig也已更新。
這就是為什么當您需要更新Roy時的原因。 首先從Neo4j獲取該記錄非常重要。 在將Craig添加到列表之前,您需要Roy隊友的最新狀態。
為什么沒有代碼可以獲取Craig并添加任何關系? 因為您已經擁有它! 格雷格(Greg)早些時候將克雷格(Craig)標記為隊友,羅伊(Roy)也是如此。 這意味著無需再次更新Craig的關系。 在遍歷每個團隊成員并將其信息打印到控制臺時,您可以看到它。
最后,查看其他查詢中您向后看的地方,回答“誰與誰一起工作?”的問題。
以下清單顯示了成品 `AccessingDataNeo4jApplication` 類(在 `src/main/java/com/example/accessingdataneo4j/AccessingDataNeo4jApplication.java`):
~~~
package com.example.accessingdataneo4j;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
@SpringBootApplication
@EnableNeo4jRepositories
public class AccessingDataNeo4jApplication {
private final static Logger log = LoggerFactory.getLogger(AccessingDataNeo4jApplication.class);
public static void main(String[] args) throws Exception {
SpringApplication.run(AccessingDataNeo4jApplication.class, args);
System.exit(0);
}
@Bean
CommandLineRunner demo(PersonRepository personRepository) {
return args -> {
personRepository.deleteAll();
Person greg = new Person("Greg");
Person roy = new Person("Roy");
Person craig = new Person("Craig");
List<Person> team = Arrays.asList(greg, roy, craig);
log.info("Before linking up with Neo4j...");
team.stream().forEach(person -> log.info("\t" + person.toString()));
personRepository.save(greg);
personRepository.save(roy);
personRepository.save(craig);
greg = personRepository.findByName(greg.getName());
greg.worksWith(roy);
greg.worksWith(craig);
personRepository.save(greg);
roy = personRepository.findByName(roy.getName());
roy.worksWith(craig);
// We already know that roy works with greg
personRepository.save(roy);
// We already know craig works with roy and greg
log.info("Lookup each person by name...");
team.stream().forEach(person -> log.info(
"\t" + personRepository.findByName(person.getName()).toString()));
List<Person> teammates = personRepository.findByTeammatesName(greg.getName());
log.info("The following have Greg as a teammate...");
teammates.stream().forEach(person -> log.info("\t" + person.getName()));
};
}
}
~~~
## 建立可執行的JAR
您可以使用Gradle或Maven從命令行運行該應用程序。 您還可以構建一個包含所有必需的依賴項,類和資源的可執行JAR文件,然后運行該文件。 生成可執行jar使得在整個開發生命周期中,跨不同環境等等的情況下,都可以輕松地將服務作為應用程序進行發布,版本控制和部署。
如果您使用Gradle,則可以通過使用以下命令運行該應用程序 `./gradlew bootRun`。 或者,您可以通過使用以下命令構建JAR文件: `./gradlew build` 然后運行JAR文件,如下所示:
~~~
java -jar build/libs/gs-accessing-data-neo4j-0.1.0.jar
~~~
如果您使用Maven,則可以通過使用以下命令運行該應用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令構建JAR文件: `./mvnw clean package` 然后運行JAR文件,如下所示:
~~~
java -jar target/gs-accessing-data-neo4j-0.1.0.jar
~~~
此處描述的步驟將創建可運行的JAR。 您還可以 構建經典的WAR文件 。
您應該看到類似于以下清單的內容(以及其他內容,例如查詢):
~~~
Before linking up with Neo4j...
Greg's teammates => []
Roy's teammates => []
Craig's teammates => []
Lookup each person by name...
Greg's teammates => [Roy, Craig]
Roy's teammates => [Greg, Craig]
Craig's teammates => [Roy, Greg]
~~~
從輸出中可以看到,(最初)沒有任何人通過任何關系被連接。 然后,在添加人員后,他們就被綁在一起了。 最后,您可以看到根據隊友查找人的便捷查詢。
## 概括
恭喜你! 您只需設置一個嵌入式Neo4j服務器,存儲一些簡單的相關實體,并開發一些快速查詢。
如果要毫不費力地使用基于超媒體的RESTful前端公開Neo4j存儲庫,請閱讀 使用REST訪問Neo4j數據 。
- springboot概述
- springboot構建restful服務
- spring構建一個RESTful Web服務
- spring定時任務
- 消費RESTful Web服務
- gradle構建項目
- maven構建項目
- springboot使用jdbc
- springboot應用上傳文件
- 使用LDNA驗證用戶
- 使用 spring data redis
- 使用 spring RabbitTemplate消息隊列
- 用no4j訪問nosql數據庫
- springboot驗證web表單
- Spring Boot Actuator構j建服務
- 使用jms傳遞消息
- springboot創建批處理服務
- spring security保護web 安全
- 在Pivotal GemFire中訪問數據
- 使用Spring Integration
- 使用springboot jpa進行數據庫操作
- 數據庫事務操作
- 操作mongodb
- springmvc+tymleaf創建web應用
- 將Spring Boot JAR應用程序轉換為WAR
- 創建異步服務
- spring提交表單
- 使用WebSocket構建交互式Web應用程序
- 使用REST訪問Neo4j數據
- jquery消費restful
- springboot跨域請求
- 消費SOAP Web服務
- springboot使用緩存
- 使用Vaadin創建CRUD UI
- 使用REST訪問JPA數據
- 使用REST訪問Pivotal GemFire中的數據
- 構建soap服務
- 使用rest訪問mongodb數據
- 構建springboot應用docker鏡像
- 從STS部署到Cloud Foundry
- springboot測試web應用
- springboot訪問mysql
- springboot編寫自定義模塊并使用
- 使用Google Cloud Pub / Sub進行消息傳遞
- 構建反應式RESTful Web服務
- 使用Redis主動訪問數據
- Spring Boot 部署到Kubernetes
- 使用反應式協議R2DBC訪問數據
- Spring Security架構
- spring構建Docker鏡像詳解
- Spring Boot和OAuth2
- springboot應用部署到k8s
- spring構建rest服務詳解