neo4j整合springboot实现基础的增删改查

neo4j整合springboot实现基础的增删改查

项目搭建

pom.xml

注意:这里使用的springboot2.3.2.RELEASE,jdk1.8,Neo4j Server version:3.5.28 (community),不同版本可能存在冲突问题,需要注意。


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.2.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.examplegroupId>
    <artifactId>neo-demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>neo-demoname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.2version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-neo4jartifactId>
        dependency>
        <dependency>
            <groupId>org.neo4jgroupId>
            <artifactId>neo4j-ogm-coreartifactId>
            <version>3.2.16version>
        dependency>
        <dependency>
            <groupId>com.google.guavagroupId>
            <artifactId>guavaartifactId>
            <version>27.0.1-jreversion>
        dependency>
        
        <dependency>
            <groupId>com.voodoodyne.jackson.jsoggroupId>
            <artifactId>jackson-jsogartifactId>
            <version>1.1version>
            <scope>compilescope>
        dependency>
    dependencies>

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

project>

application.yml

# neo4j
spring:
  data:
    neo4j:
      uri: bolt://192.168.0.118:7687
      username: neo4j
      password: 123456

启动类NeoDemoApplication

package com.example.neodemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableNeo4jRepositories(basePackages = "com.example.neodemo.dao")
@EnableTransactionManagement // 激活SDN隐式事务
public class NeoDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(NeoDemoApplication.class, args);
    }

}

业务逻辑

pojo_UserNode节点

package com.example.neodemo.model;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
import org.neo4j.ogm.annotation.*;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName: UserNode
 * @Description:
 * @Author: keke
 * @Date: 2021/6/7 11:17
 */
@JsonIdentityInfo(generator= JSOGGenerator.class)
@NodeEntity(label = "User")
public class UserNode {

    @Id
    @GeneratedValue
    private Long nodeId;

    @Property(name = "name")
    private String name;

    @Property(name = "age")
    private int age;

    @Property(name = "sex")
    private String sex;

    /*注意这个地方:并不是说加了这个注解,然后下面实现了addKnows这个方法在以后调用addKnows
    就可以实现关系的增加,这是不对的,我看了很多教程没有说明。这个addKnows方法,只有在节点未被
    添加之前,调用该方法添加关系,然后再调用UserService中的create方法,这样关系才会同时被添加到图
    数据库中。如果想实现两个已有节点之间增加关系,需要单独实现,即controller中的addKnows方法*/
    @Relationship(type = "know" ,direction = Relationship.OUTGOING)
    private Set<UserNode> knows = new HashSet<>();

    public Long getNodeId() {
        return nodeId;
    }

    public void setNodeId(Long nodeId) {
        this.nodeId = nodeId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Set<UserNode> getKnows() {
        return knows;
    }

    public void setKnows(Set<UserNode> knows) {
        this.knows = knows;
    }

    public Boolean addKnows(UserNode to){
        return this.knows.add(to);
    }

    @Override
    public String toString() {
        return "UserNode{" +
                "nodeId=" + nodeId +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }

    public UserNode() {}

}

pojo_Know关系

package com.example.neodemo.model;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
import org.neo4j.ogm.annotation.*;

/**
 * @ClassName: Know
 * @Description:
 * @Author: keke
 * @Date: 2021/6/7 11:21
 */
@JsonIdentityInfo(generator= JSOGGenerator.class)
@RelationshipEntity(type = "know")
public class Know {

    @Id
    @GeneratedValue
    private Long id;

    @StartNode
    private UserNode from;

    @EndNode
    private UserNode to;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public UserNode getFrom() {
        return from;
    }

    public void setFrom(UserNode from) {
        this.from = from;
    }

    public UserNode getTo() {
        return to;
    }

    public void setTo(UserNode to) {
        this.to = to;
    }

    public Know() {
    }

    public Know(UserNode from, UserNode to) {
        this.from = from;
        this.to = to;
    }

    @Override
    public String toString() {
        return "Know{" +
                "id=" + id +
                ", from=" + from +
                ", to=" + to +
                '}';
    }

}

持久层

注意:持久层继承Neo4jRepository即实现基础的增删改查,当然也可以自己写sql,方式与mybatis框架大同小异。

UserRepository

package com.example.neodemo.dao;

import com.example.neodemo.model.UserNode;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

/**
 * @ClassName: UserRepository
 * @Description:
 * @Author: keke
 * @Date: 2021/6/7 11:24
 */
@Repository
public interface UserRepository extends Neo4jRepository<UserNode,Long> {

//    @Query("MATCH (n:User) RETURN n ")
//    List getUserNodeList();

//    @Query("create (n:User{name:{name},age:{age},sex:{sex}}) RETURN n ")
//    UserNode addUserNode(@Param("name") String name, @Param("age")int age, @Param("sex") String sex);

    @Query("MATCH (n) WHERE id(n) = :#{#userNode.nodeId} SET n.name = :#{#userNode.name},n.age = :#{#userNode.age},n.sex = :#{#userNode.sex} RETURN n")
    UserNode updateByNode(@Param("userNode") UserNode userNode);

}

KnowRepository

package com.example.neodemo.dao;

import com.example.neodemo.model.Know;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

/**
 * @ClassName: KnowRepository
 * @Description:
 * @Author: keke
 * @Date: 2021/6/7 11:24
 */
@Repository
public interface KnowRepository extends Neo4jRepository<Know,Long> {

    @Query("MATCH (fromNode) WHERE id(fromNode) = {fromId} MATCH (toNode) WHERE id(toNode) = {toId} MATCH (fromNode)-[r]->(toNode) DELETE r")
    void deleteByNodeId(@Param(value = "fromId") long fromId, @Param(value = "toId") long toId);

}

业务层

package com.example.neodemo.service;

import com.example.neodemo.model.Know;
import com.example.neodemo.model.UserNode;

import java.util.List;
import java.util.Optional;

/**
 * @ClassName: UserService
 * @Description:
 * @Author: keke
 * @Date: 2021/6/7 11:25
 */
public interface UserService {

    /**
     * @Author keke
     * @Description 添加user节点
     * @Date 2021/6/7
     * @Param [userNode]
     * @Return com.example.neodemo.model.UserNode
     **/
    UserNode create(UserNode userNode);

    /**
     * @Author keke
     * @Description 根据id删除
     * @Date 2021/6/7
     * @Param [id]
     * @Return void
     **/
    void deleteById(Long id);

    /**
     * @Author keke
     * @Description 根据id查询
     * @Date 2021/6/7
     * @Param [id]
     * @Return java.util.Optional
     **/
    Optional<UserNode> findById(long id);

    /**
     * @Author keke
     * @Description 获取所有User节点
     * @Date 2021/6/7
     * @Param []
     * @Return java.util.List
     **/
    List<UserNode> findAll();

    /**
     * @Author keke
     * @Description 增加“知道”关系
     * @Date 2021/6/7
     * @Param [fromNode, toNode]
     * @Return com.example.neodemo.model.Know
     **/
    Know addIKnows(UserNode fromNode, UserNode toNode);

    /**
     * @Author keke
     * @Description 修改单个节点
     * @Date 2021/6/7
     * @Param [userNode]
     * @Return com.example.neodemo.model.UserNode
     **/
    UserNode updateByNode(UserNode userNode);

    /**
     * @Author keke
     * @Description 删除两个节点的关系
     * @Date 2021/6/7
     * @Param [fromId, toId]
     * @Return void
     **/
    void deleteKnowByNodeId(long fromId,long toId);

}

UserService

package com.example.neodemo.service;

import com.example.neodemo.model.Know;
import com.example.neodemo.model.UserNode;

import java.util.List;
import java.util.Optional;

/**
 * @ClassName: UserService
 * @Description:
 * @Author: keke
 * @Date: 2021/6/7 11:25
 */
public interface UserService {

    /**
     * @Author keke
     * @Description 添加user节点
     * @Date 2021/6/7
     * @Param [userNode]
     * @Return com.example.neodemo.model.UserNode
     **/
    UserNode create(UserNode userNode);

    /**
     * @Author keke
     * @Description 根据id删除
     * @Date 2021/6/7
     * @Param [id]
     * @Return void
     **/
    void deleteById(Long id);

    /**
     * @Author keke
     * @Description 根据id查询
     * @Date 2021/6/7
     * @Param [id]
     * @Return java.util.Optional
     **/
    Optional<UserNode> findById(long id);

    /**
     * @Author keke
     * @Description 获取所有User节点
     * @Date 2021/6/7
     * @Param []
     * @Return java.util.List
     **/
    List<UserNode> findAll();

    /**
     * @Author keke
     * @Description 增加“知道”关系
     * @Date 2021/6/7
     * @Param [fromNode, toNode]
     * @Return com.example.neodemo.model.Know
     **/
    Know addIKnows(UserNode fromNode, UserNode toNode);

    /**
     * @Author keke
     * @Description 修改单个节点
     * @Date 2021/6/7
     * @Param [userNode]
     * @Return com.example.neodemo.model.UserNode
     **/
    UserNode updateByNode(UserNode userNode);

    /**
     * @Author keke
     * @Description 删除两个节点的关系
     * @Date 2021/6/7
     * @Param [fromId, toId]
     * @Return void
     **/
    void deleteKnowByNodeId(long fromId,long toId);

}

UserServiceImpl

package com.example.neodemo.service.impl;

import com.example.neodemo.dao.KnowRepository;
import com.example.neodemo.dao.UserRepository;
import com.example.neodemo.model.Know;
import com.example.neodemo.model.UserNode;
import com.example.neodemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName: UserServiceImpl
 * @Description:
 * @Author: keke
 * @Date: 2021/6/7 11:27
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private KnowRepository knowRepository;

    @Override
    public UserNode create(UserNode userNode) {
        return userRepository.save(userNode);
    }

    @Override
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }

    @Override
    public Optional<UserNode> findById(long id) {
        return userRepository.findById(id);
    }

    @Override
    public List<UserNode> findAll() {
        return (List<UserNode>) userRepository.findAll();
    }

    @Override
    public Know addIKnows(UserNode fromNode, UserNode toNode) {
        Know newKnow = new Know(fromNode,toNode);
        return knowRepository.save(newKnow);
    }

    @Override
    public UserNode updateByNode(UserNode userNode) {
        return userRepository.updateByNode(userNode);
    }

    @Override
    public void deleteKnowByNodeId(long fromId, long toId) {
        knowRepository.deleteByNodeId(fromId,toId);
    }

}

表现层

UserController

package com.example.neodemo.controller;

import com.example.neodemo.model.Know;
import com.example.neodemo.model.UserNode;
import com.example.neodemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName: UserController
 * @Description:
 * @Author: keke
 * @Date: 2021/6/7 11:30
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * @Author keke
     * @Description 添加节点
     * @Date 2021/6/7
     * @Param [userNode]
     * @Return com.example.neodemo.model.UserNode
     **/
    @RequestMapping(path = "/add", method = RequestMethod.POST)
    public UserNode addUserNode(@RequestBody UserNode userNode) {
        return userService.create(userNode);
    }

    /**
     * @Author keke
     * @Description 根据id删除
     * @Date 2021/6/7
     * @Param [id]
     * @Return int
     **/
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    public int delUserNodeById(@RequestParam(value = "id") long id) {
        userService.deleteById(id);
        System.out.println(id);
        return 1;
    }

    /**
     * @Author keke
     * @Description 根据id更新
     * @Date 2021/6/7
     * @Param [userNode]
     * @Return com.example.neodemo.model.UserNode
     **/
    @RequestMapping(path = "/update", method = RequestMethod.POST)
    public UserNode updateUserNodeByNode(@RequestBody UserNode userNode) {
        return userService.updateByNode(userNode);
    }

    /**
     * @Author keke
     * @Description 根据id查询单个节点
     * @Date 2021/6/7
     * @Param [id]
     * @Return com.example.neodemo.model.UserNode
     **/
    @RequestMapping(path = "/get", method = RequestMethod.GET)
    public UserNode getUserNodeById(@RequestParam(value = "id") long id) {
        Optional<UserNode> optionalUserNode = userService.findById(id);
        if (optionalUserNode.isPresent()) {
            return optionalUserNode.get();
        } else {
            return null;
        }
    }

    /**
     * @Author keke
     * @Description 查找所有节点
     * @Date 2021/6/7
     * @Param []
     * @Return java.util.List
     **/
    @RequestMapping(path = "/list", method = RequestMethod.GET)
    public List<UserNode> getUserNodeList() {
        return userService.findAll();
    }

    /**
     * @Author keke
     * @Description 给已有的两个节点建立联系
     * @Date 2021/6/7
     * @Param [fromId, toId]
     * @Return com.example.neodemo.model.Know
     **/
    @RequestMapping(path = "/addKnows", method = RequestMethod.POST)
    public Know addKnowsById(@RequestParam(value = "from") long fromId, @RequestParam(value = "to") long toId) {
        Optional<UserNode> fromOpt = userService.findById(fromId);
        Optional<UserNode> toOpt = userService.findById(toId);
        if (fromOpt.isPresent()&&toOpt.isPresent()) {
            return userService.addIKnows(fromOpt.get(),toOpt.get());
        } else {
            return null;
        }
    }

    /**
     * @Author keke
     * @Description 删除两个节点之间的关系
     * @Date 2021/6/7
     * @Param [fromId, toId]
     * @Return java.lang.String
     **/
    @RequestMapping(path = "/delKnows", method = RequestMethod.POST)
    public String deleteKnowsByNodeId(@RequestParam(value = "from") long fromId, @RequestParam(value = "to") long toId) {
        Optional<UserNode> fromOpt =  userService.findById(fromId);
        Optional<UserNode> toOpt =  userService.findById(toId);
        if (fromOpt.isPresent()&&toOpt.isPresent()) {
            userService.deleteKnowByNodeId(fromId,toId);
            return "ok";
        } else {
            return "false";
        }
    }

}

数据库测试结果

neo4j整合springboot实现基础的增删改查_第1张图片
参考文章地址:https://blog.csdn.net/qq_33637730/article/details/107629950

你可能感兴趣的:(java,java,数据库,spring,boot)