SpringBoot整合Neo4j(SpringBoot+Mybatis+Druid+Neo4j)

前面几篇文章简单的描述了Neo4j的安装、配置及导数的内容,这篇就来写下实际项目中如何整合应用Neo4j。下面要整合的是SpringBoot+Mybatis+Druid+Neo4j这样的一个框架。废话不多说,直接开始吧(这里我用的是2018.1.8版本的IntelliJ IDEA、jdk1.8)。

第一步创建一个SpringBoot的WebService项目

打开IDEA点击Create New Project。

选择Spring Initializr,再点击Next下一步。

填写好项目信息后点Next

选择Web,勾选SpringWebServices,之后点击Next

最后点击Finish,初始的SpringBoot webservice项目就完成了

此后需要等待一小段时间让它构建完成。

完成之后其目录结构如上图所示,java包下有SpringBoot的启动类,resources下有个SpringBoot的application.propertis配置文件,而我喜欢用yml就把它改成了yml,这个视个人喜好而定。

下面可以先完善一下项目的包结构,我的包结构如下所示:

第二步:添加依赖包

需要手动添加的只有三个包,分别是Neo4j 驱动、mybatis还有druid连接池,完整POM如下:

<?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.2.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.minant</groupId>
    <artifactId>mant</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>minant-service-neo4j</name>
    <description>springBoot+mybatis+druid+neo4j</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--构建项目时添加的包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--手动添加-->
        <!--neo4j-jdbc-driver-->
        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-jdbc-driver</artifactId>
            <version>3.4.0</version> </dependency>
        <!--mybatis-spring-boot-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--  连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第三步:yml配置

有服务端口、名称、数据源连接池等,赋上yml文件:

server:
  port: 8081
  servlet:
    context-path: /
spring:
  application:
    name: service-neo4j
  http:
    encoding:
      charset: UTF-8
      enabled: true
      force: true
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: org.neo4j.jdbc.bolt.BoltDriver
    url: jdbc:neo4j:bolt://localhost:7687
    username: neo4j
    password: root
#   数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
#    validation-query: match (n) return id(n) limit 2
    testWhileIdle: false
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
  mapper-locations: classpath*:/mapper/*.xml
  config-location: classpath:mybatis-config.xml

第四步:编写代码

这里编写代码就与一般SMM项目的编写大同小异了,只不过XML中的SQL要写成查询Neo4j用的Cypher语句就行了。如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.minant.mant.mapper.MyNeo4jMapper">
    <select id="getAll" resultType="com.minant.mant.model.MovieInfoModel">
        MATCH (people:Movie)
        RETURN
          id(people) as id,
          people.title as title,
          people.tagline as tagline,
          people.released as released LIMIT 10
	</select>

    <insert id="addMovie" parameterType="com.minant.mant.form.MovieInfoForm">
        create(people:Movie{title:#{title},tagline:#{tagline},released:#{released}})
    </insert>

    <update id="updateMovie" parameterType="com.minant.mant.form.MovieInfoForm">
        match (people:Movie)
        where people.title = #{title}
        set people.tagline=#{tagline},people.released=#{released}
    </update>

    <delete id="delMovie" parameterType="com.minant.mant.form.MovieInfoForm">
        match (people:Movie)
        where people.title = #{title} delete people
    </delete>
</mapper>

第五步:接口验证

本DEMO中的测试数据为Neo4j Cypher学习中的 Movie Graph数据:

接口定义如下:

package com.minant.mant.controller;

import com.minant.mant.form.MovieInfoForm;
import com.minant.mant.model.MovieInfoModel;
import com.minant.mant.service.neo4j.Neo4jService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
/**
 * @author : MinAnt
 * @ClassName : MyNeo4jController
 * @Description :
 * @date : 2020/5/14
 **/

@RestController
public class MyNeo4jController {

    @Autowired
    private Neo4jService neo4jService;

    /**
     * 查询所有电影节点信息
     * */
    @RequestMapping("/getAll")
    public List<MovieInfoModel> getAll() {
        List<MovieInfoModel> models = neo4jService.getAll();
        return models;
    }

    /**
     * 新增电影节点
     * */
    @RequestMapping("/add")
    public int add(MovieInfoForm form) {
        form = new MovieInfoForm();
        form.setTitle("MinAntMovie");
        form.setReleased("2020");
        form.setTagline("my test add");
        int i = neo4jService.addMovie(form);
        return i;
    }

    /**
     * 修改电影节点
     * */
    @RequestMapping("/update")
    public int update(MovieInfoForm form) {
        form = new MovieInfoForm();
        form.setTitle("MinAntMovie");
        form.setReleased("2050");
        form.setTagline("my test update");
        int i = neo4jService.updateMovie(form);
        return i;
    }
    /**
     * 删除电影节点
     * */
    @RequestMapping("/delMovie")
    public int delMovie(MovieInfoForm form) {
        form = new MovieInfoForm();
        form.setTitle("MinAntMovie");
        int i = neo4jService.delMovie(form);
        return i;
    }

}

调用接口结果如下:

至此项目整合完成!

 

源码链接:https://github.com/AntMxs/MyNeo4j

### 集成 Neo4j 与 IntelliJ IDEA 进行图数据库开发 对于希望利用 Neo4j 图形数据库并借助 IntelliJ IDEA 开发环境来构建应用程序的开发者来说,有多种方式可以实现两者的无缝对接。通过安装特定插件以及配置项目依赖项,能够显著简化操作流程。 #### 安装 Neo4j 插件 IntelliJ IDEA 支持直接从其市场下载官方提供的 Neo4j 浏览器插件,这使得管理本地或远程实例变得异常简单[^1]。一旦完成安装,在 IDE 中即可轻松启动/停止服务器、执行 Cypher 查询语句甚至可视化展示查询结果集中的节点关系结构。 #### 设置 Maven 或 Gradle 构建工具 为了更好地支持基于 Spring Data Neo4j (SDN) 的应用开发工作流,建议采用主流 Java 构建自动化平台之一——Maven 或者 Gradle 来定义项目的依赖库列表。这样不仅方便版本控制还利于团队协作共享资源文件夹下的 pom.xml 或 build.gradle 文件中声明 SDN 及其他必要的第三方组件作为 compile-time dependencies。 ```xml <!-- Example POM snippet for Maven --> <dependencies> <!-- Other dependency entries --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-neo4j</artifactId> <version>${neo4j.version}</version> </dependency> <!-- More dependency entries may follow here... --> </dependencies> ``` ```groovy // Example Build Script Snippet for Gradle dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-neo4j' } ``` #### 创建实体类映射至图模型 当一切准备就绪之后就可以着手编写业务逻辑代码了。通常情况下会先设计好领域对象(Entity),再考虑如何将其持久化到 Neo4j 数据库存储系统里去。Spring Data 提供了一套简洁易懂的方式用于描述这种关联性:只需按照约定俗成的方法命名属性字段,并适当添加一些注解标记就能让框架自动处理大部分繁重的工作量。 ```java import org.neo4j.ogm.annotation.GeneratedValue; import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; @NodeEntity(label="Person") public class Person { @Id @GeneratedValue private Long id; private String name; public Person() {} // Getters & Setters omitted... } ```
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值