国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringBoot高版本(2.4及以上)集成neo4j并進行增刪改查,通俗易懂附源代碼

這篇具有很好參考價值的文章主要介紹了SpringBoot高版本(2.4及以上)集成neo4j并進行增刪改查,通俗易懂附源代碼。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

SpringBoot整合Neo4j,最新版本適用,超通俗詳細講解

0.前言

? 跟著班導師做項目的時候遇到社交網(wǎng)絡的部分,而傳統(tǒng)的關系數(shù)據(jù)庫不能很好解決數(shù)據(jù)之間的關系,因此采用圖數(shù)據(jù)的方式進行存儲。Neo4j算是主流的圖數(shù)據(jù)庫,多應用于知識圖譜、社交網(wǎng)絡等。

? 這兩天學習SpringBoot時碰到了很多問題

  • springboot集合neo4j引用了org.neo4j的包,報錯Required identifier property not found for class
  • 用SpringBoot集成neo4j,查詢報錯Could not find mappable nodes or relationships inside Record
  • org.springframework.data.neo4j.core.schema中沒有@NodeEntity,@StartNode,@EndNode
  • RelationShip無法注解在實體關系類中
  • nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.neo4j.ogm.session.SessionFactory] sessionFactory找不到

看了(128條消息) 【最新】Neo4j官方建議Spring Boot 2.4.及以上版本用Neo4j Java Driver代替The Spring Boot starter_學到一寸是一寸的博客-CSDN博客的博客后才知道是因為SpringBoot版本較高(2.4以上)時集成的Neo4j的API規(guī)則方法在變化。但是他的博客還是沒有說明如何使用類似@Node的注解,自己特意去查了Neo4j官方文檔和Spring Neo4j的官方文檔并進行總結整理發(fā)出來。


本文將解決的問題

  • SpringBoot高版本(2.4以上)+Neo4j的配置
  • 使用@Node等注解操作簡化Neo4j
  • 一些簡單的cypherQuery(很類似MySQL的SQL語句)用法解釋
  • 利用Repository(類似MyBatisPlus操作的Mapper接口)對圖數(shù)據(jù)進行CRUD
  • 不使用Repository而使用Neo4jTemplate直接對圖數(shù)據(jù)進行CRUD

TODO

  • id的生成
  • 分頁查詢

本文將會結合官網(wǎng)的一個 【導演-電影-演員】關系圖來進行實現(xiàn)。以新海誠導演的《你的名字》為例。

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

[
  {
    "n": {
"identity": 10,
"labels": [
        "Movie"
      ],
"properties": {
"tagline": "影片講述了男女高中生在夢中相遇,并尋找彼此的故事。",
"title": "你的名字"
      }
    }
  },
  {
    "n": {
"identity": 11,
"labels": [
        "Person"
      ],
"properties": {
"born": 1997,
"name": "上白石萌音"
      }
    }
  },
  {
    "n": {
"identity": 12,
"labels": [
        "Person"
      ],
"properties": {
"born": 1993,
"name": "神木隆之介"
      }
    }
  },
  {
    "n": {
"identity": 13,
"labels": [
        "Person"
      ],
"properties": {
"born": 1973,
"name": "新海誠"
      }
    }
  }
]

1.初始化Spring Boot項目添加依賴

注:本文所使用SpringBoot版本為2.7.4,Java8;(Java8+均可),neo4j的安裝不再贅述,請?zhí)崆鞍惭b配置好

1.初始化項目,添加依賴

指定對應的SpringBoot版本(注意本文適配2.4版本及以上)和相應的依賴,當然也可以后續(xù)pom依賴中添加坐標(注意pom有兩個neo4j相關的依賴)

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>Neo4jDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Neo4jDemo</name>
    <description>Neo4jDemo</description>
    <properties>
        <java.version>8</java.version>
    </properties>

    <dependencies>
        <!-- neo4j 驅(qū)動 這個需要自己手動添加一下 -->
        <dependency>
            <groupId>org.neo4j.driver</groupId>
            <artifactId>neo4j-java-driver</artifactId>
        </dependency>
        <!-- neo4j 操作實體注解需要 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>

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

2.配置Neo4j

spring:
  neo4j:
    uri: bolt://<YourNeo4jIpAddress>:7687
    authentication:
      username: <yourUserName>
      password: <yourPassword>
# 指定數(shù)據(jù)庫
  data:
    neo4j:
      database: <yourDatabase>

創(chuàng)建utils包,并在該包下創(chuàng)建ExampleCommandLineRunner來裝配Driver和Session

package com.example.neo4jdemo.utils;

import lombok.extern.slf4j.Slf4j;
import org.neo4j.driver.*;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ExampleCommandLineRunner implements CommandLineRunner {

    private final Driver driver;
    private final ConfigurableApplicationContext applicationContext;
    public final Session session;

    @Bean
    Session session(){
        return session;
    }

    // Autowire the Driver bean by constructor injection
    public ExampleCommandLineRunner(Driver driver, ConfigurableApplicationContext applicationContext) {
        this.driver = driver;
        this.applicationContext = applicationContext;
        this.session = driver.session();

    }

    @Override
    public void run(String... args) throws Exception {
    }
}

2.創(chuàng)建實體類節(jié)點

1.節(jié)點

節(jié)點介紹:

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

創(chuàng)建entity包,添加實體類:PersonEntityMovieEntity

package com.example.neo4jdemo.entity;

import lombok.Data;
import org.springframework.data.neo4j.core.schema.GeneratedValue;
import org.springframework.data.neo4j.core.schema.Id;
import org.springframework.data.neo4j.core.schema.Node;


@Node("Person")
@Data
public class PersonEntity {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private Integer born;
    public PersonEntity(Integer born, String name) {
        this.name = name;
        this.born = born;
    }
}

package com.example.neo4jdemo.entity;

import lombok.Data;
import org.springframework.data.neo4j.core.schema.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Movie實體類,一個neo4j的節(jié)點 
 */
@Node(labels = "Movie") // 標簽名,labels可以缺省
@Data
public class MovieEntity {

    @Id
    @GeneratedValue // Id自增
    private Long id;

    private final String title;

    @Property("tagline") // 映射到neo4j的屬性名
    private final String description;

    public MovieEntity(String title, String description) {
        this.id = null;// 生成node時自動生成
        this.title = title;
        this.description = description;
    }

    // 用戶指定特定的Id
    public MovieEntity withId(Long id) {
        if (this.id!= null && this.id.equals(id)) {
            return this;
        } else {
            MovieEntity newObject = new MovieEntity(this.title, this.description);
            newObject.id = id;
            return newObject;
        }
    }
}

1.withId在需要指定節(jié)點id而非自動生成時使用。

2.注意到除了id外的屬性均被final修飾,一種構造優(yōu)化,提高執(zhí)行效率:(來自Spring Data Neo4j)

This gives us a roundabout 25% performance boost over reflection. For the domain class to be eligible for such optimization, it needs to adhere to a set of constraints:

  • Types must not reside in the default or under the java package.
  • Types and their constructors must be public
  • Types that are inner classes must be static.
  • The used Java Runtime must allow for declaring classes in the originating ClassLoader. Java 9 and newer impose certain limitations.

By default, Spring Data attempts to use generated property accessors and falls back to reflection-based ones if a limitation is detected.

2.節(jié)點間的關系

關系解釋:(以ACTED_IN即參演關系為例)

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

創(chuàng)建Roles和完善MovieEntity

package com.example.neo4jdemo.entity;

import org.springframework.data.neo4j.core.schema.RelationshipId;
import org.springframework.data.neo4j.core.schema.RelationshipProperties;
import org.springframework.data.neo4j.core.schema.TargetNode;

import java.util.List;

/**
 * 定義一個關系屬性
 */
@RelationshipProperties
public class Roles {

    @RelationshipId
    private Long id;

    private final List<String> roles;

    @TargetNode // 相當于@StartNode
    private final PersonEntity person;

    // 參數(shù)1是目標關系實體節(jié)點 參數(shù)2是關系屬性
    //    Roles 參數(shù)1:Person實體,演員的出生年和姓名;參數(shù)2:演員名字列表(考慮到一個演員可能參演多個角色)
    public Roles(PersonEntity person, List<String> roles) {
        this.person = person;
        this.roles = roles;
    }

    public List<String> getRoles() {
        return roles;
    }
}

注意這些關系**@TargetNode修飾的是關系箭頭的尾部, 最終的箭頭指向是當前實體**,即TargetNode(PersonEntity)->當前定義Relationship的實體(MovieEntity)

package com.example.neo4jdemo.entity;

import lombok.Data;
import org.springframework.data.neo4j.core.schema.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Movie實體類,一個neo4j的節(jié)點 
 */
@Node(labels = "Movie") // 標簽名,labels可以缺省
@Data
public class MovieEntity {

    ...(上面 1.節(jié)點 有)

    // 定義一個關系(參演)[direction]
    @Relationship(type = "ACTED_IN", direction = Relationship.Direction.INCOMING)
    private List<Roles> actorsAndRoles = new ArrayList<>();
    // 定義一個關系(導演)
    @Relationship(type = "DIRECTED", direction = Relationship.Direction.INCOMING)
    private List<PersonEntity> directors = new ArrayList<>();
    // 注意這些關系最終的箭頭指向是當前實體,即TargetNode(PersonEntity)->當前定義Relationship的實體(MovieEntity)

}

3.CRUD

Cypher Query基本使用

了解即可,有封裝好的api使用,可以先跳過不看,看3.b部分。

  1. 創(chuàng)建
# 查詢name等于 $name 的 label為Person的實體類集合
MATCH (n:Person {name: $name}) RETURN n
或者
MATCH (n:Person) WHERE n.name = $name RETURN n 
  1. n是一個變量

  2. $name 對應map的key

  3. { } 是 where 篩選的簡寫

  4. Return 返回符合篩選條件的變量n

  5. 查找

# 查詢Person和Movie之間 關系種類為ACTED_IN且關系屬性role = $roles 的實體類集合
MATCH (person:Person) -[ relation:ACTED_IN ]-> (movie:Movie) 
WHERE relation.roles = $roles
RETURN person
等價于
MATCH (person:Person) -[ relation:ACTED_IN ]-> (:Movie) 
WHERE relation.roles = $roles
RETURN person                                         
  1. person、relation、movie是變量

  2. :Person 、:Movie 用:后面接Label,person:Person有點類似變量聲明,如果不使用完全可以省略不寫

  3. 用-[]-> 來表示關系的type以及指向

  4. 修改

# 新增屬性(Person本來只有name和born屬性,新增age屬性,一般不用)
MATCH (n:Person) 
WHERE n.name = '新海誠'
SET n.age = 50

# 修改屬性
MATCH (n:Person) 
WHERE n.name = "新津城"
SET n.name = "新海誠"

# 新增/修改多個屬性
MATCH (n:Person) 
WHERE n.name = '新海誠'
SET n.age = 50, n.name="新津城"
  1. 刪除
# 刪除屬性(一般不用)
MATCH (n:Person) 
WHERE n.name = "新津城"
REMOVE n.age
# 刪除關系(新海誠的導演關系刪除)
MATCH (n:Person) -[k:DIRECTED]-> (m:Movie)
WHERE n="新海誠"
DELETE k
# 刪除節(jié)點
MATCH (n:Person)
WHERE n.name = "新海誠"
DELETE n // 當該實體仍有關系時會報錯,必須先刪除關系再刪除節(jié)點

# 刪除節(jié)點(會刪除節(jié)點實體和他關聯(lián)的屬性)
MATCH (n:Person)
WHERE n.name = "新海誠"
DETACH DELETE n

3.a 使用Neo4jTemplate對圖數(shù)據(jù)進行CRUD

1.創(chuàng)建節(jié)點和關系
// 創(chuàng)建節(jié)點實體

MovieEntity movie = new MovieEntity("你的名字","影片講述了男女高中生在夢中相遇,并尋找彼此的故事。");// 電影實體節(jié)點

// 定義(參演)關系
// new Roles 參數(shù)1:Person實體,演員的出生年和姓名;參數(shù)2:演員名字列表(考慮到一個演員可能參演多個角色)
// 參數(shù)1是目標關系實體節(jié)點 參數(shù)2是關系屬性
Roles roles1 = new Roles(new PersonEntity(1998,"上白石萌音"), Collections.singletonList("宮水三葉"));
Roles roles2 = new Roles(new PersonEntity(1993,"神木隆之介"), Collections.singletonList("立花瀧"));
PersonEntity director = new PersonEntity(1973,"新海誠");

// 添加movie的演員實體,加入(參演)關系
movie.getActorsAndRoles().add(roles1);
movie.getActorsAndRoles().add(roles2);
movie.getDirectors().add(director);

// 存入圖數(shù)據(jù)庫持久化
neo4jTemplate.save(movie);

結果:

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

2.查詢節(jié)點
        // 查詢(不太推薦用Neo4jTemplate進行過濾查詢,因為需要手動寫cypherQuery,需要開發(fā)人員了解一下cypherQuery的寫法)
        Optional<PersonEntity> person;
        // 1. 通過id查詢
        person = neo4jTemplate.findById(12, PersonEntity.class);
        System.out.println("id為12號的Person節(jié)點:\n"+person);

        // 2. 通過屬性查詢節(jié)點,如name 需要手寫cypherQuery語句
        Map<String,Object> map = new HashMap<>();
        map.put("name","新海誠");
        // 兩種寫法都對,看個人喜好 n是一個變量隨意取,{}或者where填寫query的filter過濾條件
        person = neo4jTemplate.findOne("MATCH (n:Person {name: $name}) RETURN n",map, PersonEntity.class);
//        person = neo4jTemplate.findOne("MATCH (n:Person) WHERE n.name = $name RETURN n",map, PersonEntity.class);
        System.out.println("\n查詢名字為新海誠的Person節(jié)點:\n"+person);

        // 3. 通過屬性關系查詢節(jié)點
        map = new HashMap<>();
        map.put("roles",Collections.singletonList("宮水三葉"));
        // 方法1.使用toExecutableQuery查詢
        QueryFragmentsAndParameters parameters = new QueryFragmentsAndParameters(
                "MATCH (person:Person) -[ relation:ACTED_IN]-> (movie:Movie) \n" +
                "WHERE relation.roles = $roles\n" +
                "RETURN person",map);
        List<PersonEntity> roles = neo4jTemplate.toExecutableQuery(PersonEntity.class, parameters).getResults();
        // 方法2.使用findOne查詢
//        Optional<PersonEntity> roles = neo4jTemplate.findOne(
//                "MATCH (person:Person) -[ relation:ACTED_IN]-> (movie:Movie) \n" +
//                "WHERE relation.roles = $roles\n" +
//                "RETURN person",map,PersonEntity.class);
        
        System.out.println("\n查詢角色為“宮水三葉”的演員:\n"+roles);

結果:

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

3.更新節(jié)點信息
        Long userId = person.get().getId();// 記錄當前查詢的"新海誠"的節(jié)點id
        // 更新①---------更新“新海誠”的name為曾用名“新津誠”(這是他的曾用名)
        map.put("name","新海誠");
        map.put("usedName","新津誠");
        QueryFragmentsAndParameters queryFragmentsAndParameters =
                new QueryFragmentsAndParameters(
                        "MATCH (n:Person{name: $name}) SET n.name = $usedName",
                        map);
        neo4jTemplate.toExecutableQuery(
                PersonEntity.class,
                queryFragmentsAndParameters).getResults();
        Optional<PersonEntity> person1 = neo4jTemplate.findById(userId, PersonEntity.class);
        System.out.println("\n更新“新海誠”的name為曾用名“新津誠”(這是他的曾用名):\n"+person1);
        // 更新②---------更新“新津誠”的name為“新海誠”
        person.get().setName("新海誠");
        neo4jTemplate.save(person.get());
        Optional<PersonEntity> person2 = neo4jTemplate.findById(userId, PersonEntity.class);
        System.out.println("\n更新“新津誠”的name為“新海誠”:\n"+person2);

結果:

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

4.刪除節(jié)點
        // 刪除所有節(jié)點和關系(刪除節(jié)點會響應刪除關聯(lián)關系)[也可以用cypherQuery執(zhí)行,不再贅述]
        neo4jTemplate.deleteAll(MovieEntity.class);
        neo4jTemplate.deleteAll(PersonEntity.class);

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

上方的api根據(jù)實際情況使用,不再贅述。

5.完整代碼
/**
     * 沒有Repository情況下使用Neo4jTemplate操作數(shù)據(jù)
     * @param neo4jTemplate
     */
    @Test
    void TestNoRepository(@Autowired Neo4jTemplate neo4jTemplate){
        // 刪除所有節(jié)點和關系(刪除節(jié)點會響應刪除關聯(lián)關系),避免后續(xù)創(chuàng)建節(jié)點重復影響
        neo4jTemplate.deleteAll(MovieEntity.class);
        neo4jTemplate.deleteAll(PersonEntity.class); 
        // 創(chuàng)建節(jié)點實體
        MovieEntity movie = new MovieEntity("你的名字","影片講述了男女高中生在夢中相遇,并尋找彼此的故事。");

        // new Roles 參數(shù)1:Person實體,演員的出生年和姓名;參數(shù)2:演員名字列表(考慮到一個演員可能參演多個角色)
        // 參數(shù)1是目標關系實體節(jié)點 參數(shù)2是關系屬性
        Roles roles1 = new Roles(new PersonEntity(1998,"上白石萌音"), Collections.singletonList("宮水三葉"));
        Roles roles2 = new Roles(new PersonEntity(1993,"神木隆之介"), Collections.singletonList("立花瀧"));
        PersonEntity director = new PersonEntity(1973,"新海誠");
        // 添加movie的演員實體,加入(參演)關系
        movie.getActorsAndRoles().add(roles1);
        movie.getActorsAndRoles().add(roles2);
        movie.getDirectors().add(director);

        // 存入圖數(shù)據(jù)庫持久化
        neo4jTemplate.save(movie);

        // 查詢(不太推薦用Neo4jTemplate進行過濾查詢,因為需要手動寫cypherQuery,需要開發(fā)人員了解一下cypherQuery的寫法)
        Optional<PersonEntity> person;
        // 1. 通過id查詢
        person = neo4jTemplate.findById(12, PersonEntity.class);
        System.out.println("id為12號的Person節(jié)點:\n"+person);

        // 2. 通過屬性查詢節(jié)點,如name 需要手寫cypherQuery語句
        Map<String,Object> map = new HashMap<>();
        map.put("name","新海誠");
        // 兩種寫法都對,看個人喜好 n是一個變量隨意取,{}或者where填寫query的filter過濾條件
        person = neo4jTemplate.findOne("MATCH (n:Person {name: $name}) RETURN n",map, PersonEntity.class);
//        person = neo4jTemplate.findOne("MATCH (n:Person) WHERE n.name = $name RETURN n",map, PersonEntity.class);
        System.out.println("\n查詢名字為新海誠的Person節(jié)點:\n"+person);

        // 3. 通過屬性關系查詢節(jié)點
        map = new HashMap<>();
        map.put("roles",Collections.singletonList("宮水三葉"));
        // 方法1.使用toExecutableQuery查詢
        QueryFragmentsAndParameters parameters = new QueryFragmentsAndParameters(
                "MATCH (person:Person) -[ relation:ACTED_IN]-> (movie:Movie) \n" +
                "WHERE relation.roles = $roles\n" +
                "RETURN person",map);
        List<PersonEntity> roles = neo4jTemplate.toExecutableQuery(PersonEntity.class, parameters).getResults();
        // 方法2.使用findOne查詢
//        Optional<PersonEntity> roles = neo4jTemplate.findOne(
//                "MATCH (person:Person) -[ relation:ACTED_IN]-> (movie:Movie) \n" +
//                "WHERE relation.roles = $roles\n" +
//                "RETURN person",map,PersonEntity.class);
        System.out.println("\n查詢角色為“宮水三葉”的演員:\n"+roles);

        Long userId = person.get().getId();// 記錄當前查詢的"新海誠"的節(jié)點id
        // 更新①---------更新“新海誠”的name為曾用名“新津誠”(這是他的曾用名)
        map.put("name","新海誠");
        map.put("usedName","新津誠");
        QueryFragmentsAndParameters queryFragmentsAndParameters =
                new QueryFragmentsAndParameters(
                        "MATCH (n:Person{name: $name}) SET n.name = $usedName",
                        map);
        neo4jTemplate.toExecutableQuery(
                PersonEntity.class,
                queryFragmentsAndParameters).getResults();
        Optional<PersonEntity> person1 = neo4jTemplate.findById(userId, PersonEntity.class);
        System.out.println("\n更新“新海誠”的name為曾用名“新津誠”(這是他的曾用名):\n"+person1);
        // 更新②---------更新“新津誠”的name為“新海誠”
        person.get().setName("新海誠");
        neo4jTemplate.save(person.get());
        Optional<PersonEntity> person2 = neo4jTemplate.findById(userId, PersonEntity.class);
        System.out.println("\n更新“新津誠”的name為“新海誠”:\n"+person2);

    }

3.b 使用repository對圖數(shù)據(jù)進行CRUD

1.創(chuàng)建Repository

新建repository包,創(chuàng)建PersonRepositoryMovieRepository

package com.example.neo4jdemo.repository;

import com.example.neo4jdemo.entity.PersonEntity;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRepository extends Neo4jRepository<PersonEntity, Long> {
}
package com.example.neo4jdemo.repository;

import com.example.neo4jdemo.entity.MovieEntity;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MovieRepository extends Neo4jRepository<MovieEntity, Long> {
}

2.創(chuàng)建節(jié)點和關系

// 創(chuàng)建節(jié)點
MovieEntity movie = new MovieEntity("你的名字","影片講述了男女高中生在夢中相遇,并尋找彼此的故事。");
Roles roles1 = new Roles(new PersonEntity(1998,"上白石萌音"), Collections.singletonList("宮水三葉"));
Roles roles2 = new Roles(new PersonEntity(1993,"神木隆之介"), Collections.singletonList("立花瀧"));
PersonEntity director = new PersonEntity(1973,"新海誠");
// 添加關系
movie.getActorsAndRoles().add(roles1);
movie.getActorsAndRoles().add(roles2);
movie.getDirectors().add(director);
// 存入圖數(shù)據(jù)庫持久化
movieRepository.save(movie);

3.查詢

需求:根據(jù)Person的名字查詢對應節(jié)點

PersonRepository中添加方法:

@Repository
public interface PersonRepository extends Neo4jRepository<PersonEntity, Long> {
    PersonEntity findPersonEntityByName(String name);
}

MovieRepository中添加方法:

@Repository
public interface MovieRepository extends Neo4jRepository<MovieEntity, Long> {

//    @Query("MATCH (n:Movie) WHERE id(n) = $0 RETURN n") 這種方法是自己寫Query語句進行查詢
    List<MovieEntity> findMovieEntitiesById(Long id);
    MovieEntity findMovieEntityByTitle(String title);
}

查詢:

// 查詢
        // 查詢
        PersonEntity person = personRepository.findPersonEntityByName("上白石萌音");
        System.out.println("查詢名字為“上白石萌音”的PersonEntity:"+person);
        MovieEntity movieQueried = movieRepository.findMovieEntityByTitle("你的名字");
        System.out.println("查詢名字為“你的名字”的MovieEntity:"+movieQueried);

結果:

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

查詢名字為“上白石萌音”的PersonEntity:
PersonEntity(id=15, name=上白石萌音, born=1998)

查詢名字為“你的名字”的MovieEntity:
MovieEntity(id=14, title=你的名字, description=影片講述了男女高中生在夢中相遇,并尋找彼此的故事。, actorsAndRoles=[com.example.neo4jdemo.entity.Roles@d902300, com.example.neo4jdemo.entity.Roles@2db33feb], directors=[PersonEntity(id=17, name=新海誠, born=1973)])

4.更新

        // 更新(更新主要是三步:1.獲取實體id;2.修改實體屬性;3.更新實體)
        // 注意:repository的save方法【對應的實體若id一致】則為修改,否則為新建。
        Long personId = person.getId();
        person.setBorn(1997);
        personRepository.save(person);
        person = personRepository.findPersonEntityByName("上白石萌音");
        System.out.println(personId == person.getId()?"\n更新“上白石萌音”出生日期為1997信息成功?。篭n"+person:"更新信息失??!");

could not find mappable nodes or relationships inside record,neo4j,spring boot,知識圖譜,經(jīng)驗分享

5.刪除

        // 刪除所有節(jié)點和關系
        movieRepository.deleteAll();
        personRepository.deleteAll();

6.完整代碼

/**
 * 使用repository操作圖數(shù)據(jù)
 */
@Test
void testByRepository(@Autowired MovieRepository movieRepository, @Autowired PersonRepository personRepository){
    // 刪除所有節(jié)點和關系(刪除節(jié)點會響應刪除關聯(lián)關系),避免后續(xù)創(chuàng)建節(jié)點重復影響
    movieRepository.deleteAll();
    personRepository.deleteAll();

    // 創(chuàng)建節(jié)點
    MovieEntity movie = new MovieEntity("你的名字","影片講述了男女高中生在夢中相遇,并尋找彼此的故事。");
    Roles roles1 = new Roles(new PersonEntity(1998,"上白石萌音"), Collections.singletonList("宮水三葉"));
    Roles roles2 = new Roles(new PersonEntity(1993,"神木隆之介"), Collections.singletonList("立花瀧"));
    PersonEntity director = new PersonEntity(1973,"新海誠");
    // 添加關系
    movie.getActorsAndRoles().add(roles1);
    movie.getActorsAndRoles().add(roles2);
    movie.getDirectors().add(director);
    // 存入圖數(shù)據(jù)庫持久化
    movieRepository.save(movie);

    // 查詢
    PersonEntity person = personRepository.findPersonEntityByName("上白石萌音");
    System.out.println("\n查詢名字為“上白石萌音”的PersonEntity:\n"+person);
    MovieEntity movieQueried = movieRepository.findMovieEntityByTitle("你的名字");
    System.out.println("\n查詢名字為“你的名字”的MovieEntity:\n"+movieQueried);

    // 更新(更新主要是三步:1.獲取實體id;2.修改實體屬性;3.更新實體)
    // 注意:repository的save方法【對應的實體若id一致】則為修改,否則為新建。
    Long personId = person.getId();
    person.setBorn(1997);
    personRepository.save(person);
    person = personRepository.findPersonEntityByName("上白石萌音");
    System.out.println(personId == person.getId()?"\n更新“上白石萌音”出生日期為1997信息成功?。篭n"+person:"更新信息失??!");
}

4.參考與源碼

案例來自官方文檔:

https://docs.spring.io/spring-data/neo4j/docs/current/reference/html/#conversions
https://neo4j.com/docs/aura/auradb/connecting-applications/spring-boot/

源碼戳這里:

https://github.com/WuYiheng-Og/neo4j_springboot文章來源地址http://www.zghlxwxcb.cn/news/detail-788720.html

到了這里,關于SpringBoot高版本(2.4及以上)集成neo4j并進行增刪改查,通俗易懂附源代碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • neo4j各個版本下載

    ** neo4j各個版本下載地址 歷史版本下載 https://we-yun.com/doc/neo4j/

    2024年02月13日
    瀏覽(32)
  • springboot+neo4j

    請通過依賴項管理包含啟動器模塊并配置要使用的 Bolt URL,例如 spring.neo4j.uri=bolt://localhost:7687 。啟動器假設服務器已禁用身份驗證。由于 SDN 啟動器依賴于 Java 驅(qū)動程序的啟動器,因此此處所說的有關配置的所有內(nèi)容也適用于此處。有關可用屬性的參考,請在 spring.neo4j 命名

    2024年01月20日
    瀏覽(28)
  • 圖數(shù)據(jù)庫Neo4j——SpringBoot使用Neo4j & 簡單增刪改查 & 復雜查詢初步

    圖數(shù)據(jù)庫Neo4j——SpringBoot使用Neo4j & 簡單增刪改查 & 復雜查詢初步

    圖形數(shù)據(jù)庫是專門用于存儲圖形數(shù)據(jù)的數(shù)據(jù)庫,它使用圖形模型來存儲數(shù)據(jù),并且支持復雜的圖形查詢。常見的圖形數(shù)據(jù)庫有Neo4j、OrientDB等。 Neo4j是用Java實現(xiàn)的開源NoSQL圖數(shù)據(jù)庫,本篇博客介紹如何在SpringBoot中使用Neo4j圖數(shù)據(jù)庫,如何進行簡單的增刪改查,以及如何進行復雜

    2024年02月06日
    瀏覽(34)
  • neo4j jdk安裝版本搭配

    neo4j jdk安裝版本搭配

    jdk下載版本為jdk11 neo4j 為neo4j-community-4.3.15 可使用 非常流暢 沒有毛?。。。?這里直接給出結論,對于想知道這兩個版本為什么適配的小伙伴可以繼續(xù)往下看 出現(xiàn)這個界面后在網(wǎng)頁打開browser 輸入賬號和密碼后就可以登錄了(環(huán)境變量的配置各位可以參考別的博主沒什么區(qū)別

    2024年02月01日
    瀏覽(13)
  • SpringBoot整合Neo4j

    Neo4j是一個高性能的,NOSQL圖形數(shù)據(jù)庫,它的內(nèi)部就是一個高性能的圖形引擎,專門為應用程序提供嵌入式,磁盤的高性能存儲和遍歷圖形結構的能力。Spring Boot是一個旨在簡化創(chuàng)建獨立的,生產(chǎn)級別的Spring基礎應用程序的開發(fā)框架。在本文中,我們將探討如何在Spring Boot項目

    2024年02月06日
    瀏覽(22)
  • 安裝win版本的neo4j(2023最新版本)

    安裝win版本的neo4j(2023最新版本)

    誰能想到最后還是學知識圖譜了呢,真是啥都要學啊,躲不過~ 參考:https://blog.csdn.net/qq_38335648/article/details/115027676 Neo4j是一個高性能的NOSQL圖形數(shù)據(jù)庫,它將結構化數(shù)據(jù)存儲在網(wǎng)絡上而不是表中。由于知識圖譜中存在大量的關系型信息(實體—關系—實體), 使用結構化數(shù)據(jù)

    2024年02月08日
    瀏覽(26)
  • 圖數(shù)據(jù)庫Neo4j——Neo4j簡介、數(shù)據(jù)結構 & Docker版本的部署安裝 & Cypher語句的入門

    圖數(shù)據(jù)庫Neo4j——Neo4j簡介、數(shù)據(jù)結構 & Docker版本的部署安裝 & Cypher語句的入門

    MySQL是一種開源的關系型數(shù)據(jù)庫管理系統(tǒng),使用SQL作為其查詢語言,常見的關系型數(shù)據(jù)庫有MySQL、Oracle、SQL Server、PostgreSQL等。相關博客文章如下: 【合集】MySQL的入門進階強化——從 普通人 到 超級賽亞人 的 華麗轉身 PostgreSQL數(shù)據(jù)庫——Docker版本的postgres安裝 Navicat連接方式

    2024年02月06日
    瀏覽(51)
  • spring boot集成neo4j實現(xiàn)簡單的知識圖譜

    spring boot集成neo4j實現(xiàn)簡單的知識圖譜

    隨著社交、電商、金融、零售、物聯(lián)網(wǎng)等行業(yè)的快速發(fā)展,現(xiàn)實社會織起了了一張龐大而復雜的關系網(wǎng),傳統(tǒng)數(shù)據(jù)庫很難處理關系運算。大數(shù)據(jù)行業(yè)需要處理的數(shù)據(jù)之間的關系隨數(shù)據(jù)量呈幾何級數(shù)增長,急需一種支持海量復雜數(shù)據(jù)關系運算的數(shù)據(jù)庫,圖數(shù)據(jù)庫應運而生。 世界

    2024年03月12日
    瀏覽(25)
  • springboot整合neo4j模糊查詢

    1.場景 查詢與content相似的實體 解決方案: 1.直接從neo4j中查詢所有實體并使用杰卡德相似度算法計算相似度,返回top n,該方案由于要匹配圖中所有實體,性能較差。 2.模糊查詢neo4j中的實體,并對查詢結果與content做相似度計算,相似度算法為hutool中的TextSimilarity.similar()接口

    2024年02月13日
    瀏覽(24)
  • 【使用Neo4j進行圖數(shù)據(jù)可視化】

    【使用Neo4j進行圖數(shù)據(jù)可視化】

    ?? 算法題 ?? ?? 算法刷題專欄 | 面試必備算法 | 面試高頻算法 ?? ?? 越難的東西,越要努力堅持,因為它具有很高的價值,算法就是這樣? ?? 作者簡介:碩風和煒,CSDN-Java領域優(yōu)質(zhì)創(chuàng)作者??,保研|國家獎學金|高中學習JAVA|大學完善JAVA開發(fā)技術棧|面試刷題|面經(jīng)八股文

    2024年02月13日
    瀏覽(18)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包