1.Java 操作neo4j

1. 引入pom

        <!-- neo4j 相关的API -->
        <dependency>
            <groupId>org.neo4j.driver</groupId>
            <artifactId>neo4j-java-driver</artifactId>
            <version>1.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j</artifactId>
            <version>3.3.4</version>
        </dependency>

2. 测试查询

 其他创建、建立关系类似

package com.xm.ggn.test.neo4j;

import org.neo4j.driver.v1.*;

public class Neo4jTest {

    public static void main(String[] args) {
        Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "neo4j."));
        Session session = driver.session();
        // 查询
        StatementResult result = session.run("MATCH (a:Student) WHERE a.name = \"佩奇\" RETURN a.name as name, a.sex as sex");
        while (result.hasNext()) {
            Record record = result.next();
            String name = record.get("name").asString();
            String sex = record.get("sex").asString();
            System.out.println(name + "\t" + sex);
        }
        session.close();
        driver.close();
    }
}

结果:

佩奇 男

2. Springboot 整合neo4j

 1. pom引入如下:

        <!-- neo4j -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>

2. 增加配置类:

package com.xm.ggn.config;

import org.neo4j.ogm.session.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.transaction.Neo4jTransactionManager;

@Configuration
@EnableNeo4jRepositories("com.xm") // 声明neo4j repository存放地址
public class Neo4jConfig {

    @Value("${spring.data.neo4j.uri}")
    private String uri;
    @Value("${spring.data.neo4j.username}")
    private String userName;
    @Value("${spring.data.neo4j.password}")
    private String password;

    @Bean
    public org.neo4j.ogm.config.Configuration getConfiguration() {
        org.neo4j.ogm.config.Configuration configuration = new org.neo4j.ogm.config.Configuration.Builder().uri(uri).connectionPoolSize(100).credentials(userName, password).withBasePackages("com.xm").build();
        return configuration;
    }

    @Bean
    public SessionFactory sessionFactory() {
        return new SessionFactory(getConfiguration());
    }

    @Bean("neo4jTransaction")
    public Neo4jTransactionManager neo4jTransactionManager(SessionFactory sessionFactory) {
        return new Neo4jTransactionManager(sessionFactory);
    }
}

3. 增加相关类

(1) bean 实体类

Group 班级标签:

package com.xm.ggn.test.neo4j.neo4j.springdata.entity;

import org.neo4j.ogm.annotation.*;

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

/**
 * 有点类似于Mysql中的table 映射的对象类,mysql中叫做ORM,neo4j中叫做OGM [object graph mapping]
 */
@NodeEntity("group") // 指定label是 group
public class GroupNode {

    @Id
    @GeneratedValue
    private Long id;

    /**
     * 班级名称
     */
    @Property(name = "name")
    private String name;

    /**
     * 编号
     */
    private String num;

    @Relationship(type = "RelationEdge")
    private Set<RelationEdge> sets = new HashSet<>();

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getNum() {
        return num;
    }

    public void setNum(String num) {
        this.num = num;
    }

    public Set<RelationEdge> getSets() {
        return sets;
    }

    public void setSets(Set<RelationEdge> sets) {
        this.sets = sets;
    }

    public void addRelation(StudentNode sonNode, String name) {
        RelationEdge relationNode = new RelationEdge(this, sonNode, name);
        sets.add(relationNode);
        sonNode.getSets().add(relationNode);
    }
}

Student 学生标签:

package com.xm.ggn.test.neo4j.neo4j.springdata.entity;

import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;

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

/**
 * 有点类似于Mysql中的table 映射的对象类,mysql中叫做ORM,neo4j中叫做OGM [object graph mapping]
 */
@NodeEntity("student") // 指定label是 student
public class StudentNode {

    @Id
    @GeneratedValue
    private Long id;

    /**
     * 学生名称
     */
    private String name;

    /**
     * 性别
     */
    private String sex;

    @Relationship(type = "RelationEdge", direction = "INCOMING")
    private Set<RelationEdge> sets = new HashSet<>();

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

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

    public Set<RelationEdge> getSets() {
        return sets;
    }

    public void setSets(Set<RelationEdge> sets) {
        this.sets = sets;
    }
}

RelationEdge 关系边:

package com.xm.ggn.test.neo4j.neo4j.springdata.entity;

import lombok.Data;
import org.neo4j.ogm.annotation.*;

@RelationshipEntity(type = "RelationEdge")
@Data
public class RelationEdge {

    @Id
    @GeneratedValue
    private Long id;

    // 关系名
    private String name;

    @StartNode
    private GroupNode groupNode;

    @EndNode
    private StudentNode studentNode;

    public RelationEdge(GroupNode parentNode, StudentNode sonNode, String name) {
        this.groupNode = parentNode;
        this.studentNode = sonNode;
        this.name = name;
    }
}

GroupDao:

package com.xm.ggn.test.neo4j.neo4j.springdata.dao;


import com.xm.ggn.test.neo4j.neo4j.springdata.entity.GroupNode;
import org.springframework.data.neo4j.repository.Neo4jRepository;

public interface GroupDao extends Neo4jRepository<GroupNode, Long> {
}

StudentDao:

package com.xm.ggn.test.neo4j.neo4j.springdata.dao;


import com.xm.ggn.test.neo4j.neo4j.springdata.entity.StudentNode;
import org.springframework.data.neo4j.repository.Neo4jRepository;

public interface StudentDao extends Neo4jRepository<StudentNode, Long> {
}

Neo4jController:

package com.xm.ggn.test.neo4j.neo4j.springdata.controller;

import com.xm.ggn.test.neo4j.neo4j.springdata.dao.GroupDao;
import com.xm.ggn.test.neo4j.neo4j.springdata.dao.StudentDao;
import com.xm.ggn.test.neo4j.neo4j.springdata.entity.GroupNode;
import com.xm.ggn.test.neo4j.neo4j.springdata.entity.RelationEdge;
import com.xm.ggn.test.neo4j.neo4j.springdata.entity.StudentNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

@RestController
@RequestMapping("/node")
public class Neo4jController {

    @Autowired
    private GroupDao groupDap;

    @Autowired
    private StudentDao studentDap;

    @GetMapping(value = "/create")
    public void createNodeRelation() {
        StudentNode studentNode1 = new StudentNode();
        studentNode1.setName("佩奇");
        studentNode1.setSex("男");
        StudentNode studentNode2 = new StudentNode();
        studentNode2.setName("神经");
        studentNode2.setSex("女");
        studentDap.save(studentNode1);
        studentDap.save(studentNode2);

        GroupNode groupNode = new GroupNode();
        groupNode.setName("宏哥班");
        groupNode.setNum("298");
        // 增加关系
        groupNode.addRelation(studentNode1, "includes");
        groupNode.addRelation(studentNode2, "includes");
        groupDap.save(groupNode);
    }

    @GetMapping(value = "/find")
    public void findNodes() {
        Iterable<GroupNode> parentNodes = groupDap.findAll();
        for (GroupNode parentNode : parentNodes) {
            Set<RelationEdge> relationNodeSet = parentNode.getSets();
            for (RelationEdge relationNode : relationNodeSet) {
                System.out.println("id:" + parentNode.getId() + " name:" + parentNode.getName() + " 关系:" + relationNode.getName() + "子节点:" + relationNode.getStudentNode().getName());
            }
        }
    }
}

结果:

(1) 测试创建

$ curl http://localhost:8088/node/create
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    59    0    59    0     0      6      0 --:--:--  0:00:09 --:--:--    17{                 "success":true,"data":null,"msg":"成功","errorCode":"0"}

 

到neo4j查看:

MATCH (n) RETURN n LIMIT 25

 

结果:

Java操作Neo4j & Springboot 整合neo4j_springboot

(2) 测试查询

$ curl http://localhost:8088/node/find
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    59    0    59    0     0    236      0 --:--:-- --:--:-- --:--:--   252{"success":true,"data":null,"msg":"成功","errorCode":"0"}

控制台日志:

id:3 name:宏哥班 关系:includes子节点:神经
id:3 name:宏哥班 关系:includes子节点:佩奇

补充: 还可以自己手动写CQL

    @Autowired
    private Session session;

    @GetMapping(value = "/create2")
    public void createNodeRelation2() {
        String cypherSQL = "create (n:student{name: '瓜哥', sex: '男'})";
        session.query(cypherSQL, new HashMap<>());
        String mergeSQL = "match (a:student{name: '瓜哥'}), (b:group{num: '298'}) merge(a)-[:belongsto]->(b)";
        session.query(mergeSQL, new HashMap<>());
    }

补充:Neo4j 自动配置原理

     其自动配置是在类org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration里面的,其默认的配置属性是在:Neo4jProperties

 

【当你用心写完每一篇博客之后,你会发现它比你用代码实现功能更有成就感!】