首页 > 其他分享 >Springboot内嵌neo4j配置

Springboot内嵌neo4j配置

时间:2023-08-20 16:57:11浏览次数:36  
标签:内嵌 Springboot tx org ColumnVertex import neo4j name

环境说明

MacOS Apple M1 | Jdk17 | Maven 3.8.5 | SpringBoot 2.6.9 | neo4j 5.10.0
注:neo4j 内嵌最大的坑就是版本兼容性,所以引入前一定检查 neo4j 与 springboot 版本兼容性,其次 neo4j 各版本间配置使用上,区别也挺大的,本文只针对特定版本,因此建议更多参考官网文档,有最新的配置使用方法。

配置

pom.xml

<dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j</artifactId>
    <version>5.10.0</version>
</dependency>

Configuration

import org.neo4j.dbms.api.DatabaseManagementService;
import org.neo4j.dbms.api.DatabaseManagementServiceBuilder;
import org.neo4j.graphdb.GraphDatabaseService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.file.Path;

import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME;

@Configuration
public class Neo4jConfig {

  @Bean
  public GraphDatabaseService graphDatabaseService() {
    // graph.db 为自定义 neo4j 库目录位置
    DatabaseManagementService managementService =
        new DatabaseManagementServiceBuilder(Path.of("graph.db")).build();
    GraphDatabaseService graphDb = managementService.database(DEFAULT_DATABASE_NAME);
    registerShutdownHook(managementService);
    return graphDb;
  }

  private static void registerShutdownHook(final DatabaseManagementService managementService) {
    // 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(() -> managementService.shutdown()));
  }
}

自定义节点 实现通用方法

neo4j 可以对每个图节点自动生成一个唯一 id,也支持通过 @Id 自定义 id

// Node
public class ColumnVertex {
    private String name;
}

// Service
public interface EmbeddedGraphService {
    // 添加图节点
    void addColumnVertex(ColumnVertex currentVertex, ColumnVertex upstreamVertex);
    // 寻找上游节点
    List<ColumnVertex> findUpstreamColumnVertex(ColumnVertex currentVertex);
    // 寻找下游节点
    List<ColumnVertex> findDownstreamColumnVertex(ColumnVertex currentVertex);
}

// Impl
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;
import org.springframework.stereotype.Service;

@Service
public class EmbeddedGraphServiceImpl implements EmbeddedGraphService {

  @Resource private GraphDatabaseService graphDb;

  @Override
  public void addColumnVertex(ColumnVertex currentVertex, ColumnVertex upstreamVertex) {
    try (Transaction tx = graphDb.beginTx()) {
      tx.execute(
          "MERGE (c:ColumnVertex {name: $currentName}) MERGE (u:ColumnVertex {name: $upstreamName})"
              + " MERGE (u)-[:UPSTREAM]->(c)",
          Map.of("currentName", currentVertex.getName(), "upstreamName", upstreamVertex.getName()));
      tx.commit();
    }
  }

  @Override
  public List<ColumnVertex> findUpstreamColumnVertex(ColumnVertex currentVertex) {
    List<ColumnVertex> result = new ArrayList<>();
    try (Transaction tx = graphDb.beginTx()) {
      Result queryResult =
          tx.execute(
              "MATCH (u:ColumnVertex)-[:UPSTREAM]->(c:ColumnVertex) WHERE c.name = $name RETURN"
                  + " u.name AS name",
              Map.of("name", currentVertex.getName()));
      while (queryResult.hasNext()) {
        Map<String, Object> row = queryResult.next();
        result.add(new ColumnVertex().setName((String) row.get("name")));
      }
      tx.commit();
    }
    return result;
  }

  @Override
  public List<ColumnVertex> findDownstreamColumnVertex(ColumnVertex currentVertex) {
    List<ColumnVertex> result = new ArrayList<>();
    try (Transaction tx = graphDb.beginTx()) {
      Result queryResult =
          tx.execute(
              "MATCH (c:ColumnVertex)-[:UPSTREAM]->(d:ColumnVertex) WHERE c.name = $name RETURN"
                  + " d.name AS name",
              Map.of("name", currentVertex.getName()));
      while (queryResult.hasNext()) {
        Map<String, Object> row = queryResult.next();
        result.add(new ColumnVertex().setName((String) row.get("name")));
      }
      tx.commit();
    }
    return result;
  }
}

如何创建唯一键

这里使用 name ColumnVertex 的唯一键,在启动服务时检查是否存在唯一键,不存在则创建

@Service
public class EmbeddedGraphServiceImpl implements EmbeddedGraphService {

    @Resource private GraphDatabaseService graphDb;

    @PostConstruct
  public void init() {
    try (Transaction tx = graphDb.beginTx()) {
      Result result = tx.execute("SHOW CONSTRAINTS");
      boolean constraintExists = false;
      while (result.hasNext()) {
        Map<String, Object> row = result.next();
        if (((List<Object>) row.get("labelsOrTypes")).contains("ColumnVertex")
            && ((List<Object>) row.get("properties")).contains("name")
            && "UNIQUENESS".equals(row.get("type"))) {
          constraintExists = true;
          break;
        }
      }
      if (!constraintExists) {
        tx.execute("CREATE CONSTRAINT FOR (c:ColumnVertex) REQUIRE c.name IS UNIQUE");
      }
      tx.commit();
    }
  }
}

标签:内嵌,Springboot,tx,org,ColumnVertex,import,neo4j,name
From: https://www.cnblogs.com/pandacode/p/17644239.html

相关文章

  • springboot添加启动事件监听
    当我们需要在springboot启动时做的第一件事,可以通过添加事件监听实现,具体如下:添加事件importorg.springframework.boot.context.event.ApplicationStartingEvent;importorg.springframework.context.ApplicationListener;publicclassMyEventimplementsApplicationLis......
  • Springboot 内嵌 Sqlite 配置使用
    版本号MacOSAppleM1|Jdk17|Maven3.8.5|SpringBoot2.6.9|Sqlite3.42.0.0pom.xml<dependencies><dependency><groupId>org.xerial</groupId><artifactId>sqlite-jdbc</artifactId>......
  • JAVAEE就业免费视频教程springboot综合案例
    day06_springboot综合案例资源权限管理查询资源权限查询资源权限执行流程编写PermissionMapper接口publicinterfacePermissionMapper{/***查询资源权限*/List<Permission>findAll();}编写PermissionServicepublicinterfacePermissionServi......
  • java语言B/S医院HIS系统源码【springboot】
     医院云HIS全称为基于云计算的医疗卫生信息系统(Cloud-BasedHealthcareInformationSystem),是运用云计算、大数据、物联网等新兴信息技术,按照现代医疗卫生管理要求,在一定区域范围内以数字化形式提供医疗卫生行业数据收集、存储、传递、处理的业务和技术平台,实现区域内医疗卫......
  • SpringBoot使用jasypt实现数据库配置加密
    我们在日常使用中有需要加密设置数据库连接配置的情况,我们可以使用第三方的依赖jasypt来实现我们的数据库配置加密,从而提高系统的安全性。一、引入jasypt依赖<!--jasypt--><dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</......
  • 基于springboot校园管理系统的设计与实现
    研究的内容目前许多人仍将传统的纸质工具作为信息管理的主要工具,而网络技术的应用只是起到辅助作用。在对网络工具的认知程度上,较为传统的office软件等仍是人们使用的主要工具,而相对全面且专业的校园管理系统的信息管理软件仍没有得到大多数人的了解或认可。本选题宗旨在通过标签分......
  • 基于SpringBoot的在线视频教育平台的设计与实现
    拟解决的问题:(1)根据指导老师提供的原始材料和课题要求按照管理信息系统的生命周期开发方法和步骤,经过细致的系统分析、合理的系统设计,高效率的系统试试,引发web开发的思想,选择可行的开发工具,实现在线教育平台。本课题充分利用面向对象开发环境的可视化特点,合理的设计用户界面,按照数......
  • 基于springboot房产销售系统
    房产销售也都将通过计算机进行整体智能化操作,对于房产销售系统所牵扯的管理及数据保存都是非常多的,例如管理员;首页、个人中心、用户管理、销售经理管理、房源信息管理、房源类型管理、房子户型管理、交易订单管理、预约看房管理、评价管理、我的收藏管理、系统管理,用户;首页、个人中......
  • 基于Springboot学生读书笔记共享
    本文主要论述了如何使用JAVA语言开发一个读书笔记共享平台,本系统将严格按照软件开发流程进行各个阶段的工作,采用B/S架构,面向对象编程思想进行项目开发。在引言中,作者将论述读书笔记共享平台的当前背景以及系统开发的目的,后续章节将严格按照软件开发流程,对系统进行各个阶段分析设计......
  • 基于springboot母婴商城
    课题简介本课题后端使用SpringBoot+SpringCloud框架,前端采用html,JQuery,JS,DIV+CSS技术进行编程,设计在线商城。系统具有前台和后台两大服务。前台主要有用户登录注册、浏览商品、加入购物车、提交订单、支付等模块;后台主要有商品管理、用户管理、订单管理、分类管理等模块。课题内容......