Java操作Neo4J就是这么简单

Java
223
0
0
2023-06-08

使用 java 操作 Neo4j

首先我们先使用原生的这种方式,导入 jar 包,然后:

 public class TestController {  
  public  static   void  main(String[] args) {    
    Driver driver = GraphDatabase.driver("bolt://localhost:", AuthTokens.basic(" neo4j ", "Yinlidong1995."));
    Session session = driver.session();      
    session.run("CREATE (n:Part {name: {name},title: {title}})",                
                parameters( "name", "Arthur", "title", "King001" ));     
    StatementResult result =  session .run( "MATCH (a:Part) WHERE a.name = {name} " +                       
                                         "RETURN a.name AS name, a.title AS title",       
    parameters( "name", "Arthur"));      
    while (result.hasNext()) {          
      Record record = result.next();           
      System.out.println( record.get( "title" ).asString() + "
                         " + record.get( "name" ).asString() );      
     }       
     session.close();
     driver.close();  
   }
} 

这是一种比较古老的方式,来实现的,而且还是需要些 CQL 语句来进行实现。但是胜在非常好理解,这个时候,我们需要再来看看图,看看在 Neo4J 中他是怎么展现的。

通过这个,我们至少证明我们成功连上了,并且创建也成功了。

这时候有细心的读者就会问,为啥我之前在 ​GraphDatabase.driver​ ​ 的地方,连接的是

​bolt://localhost:7687​ ​.

这是因为,你启动的Neo4J 是7474,也就是说,Neo4J 服务里面可不是这个来连接,

Spring Boot 整合 Neo4j

1.创建SpringBoot项目

常规的创建SpringBoot项目,

创建完成之后,习惯性的要改一下 SpringBoot 的版本号,最好别用最新的,因为阿粉亲身经历,使用最新版的,出现了错误你都不知道怎么出现的,就是这么神奇,你永远都发现不了的bug。

我们把版本号改成2.1.0,这样的话,我们在 pom 文件中加入依赖 jar

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

<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>.16.10</version>
</dependency> 

2.增加配置

 spring:  
  data:    
  neoj:     
  url: bolt://localhost:    
  username: neoj   
  password: Yinlidong.  
  main:   
   allow-bean-definition-overriding: true 

3.Neo4JConfig

 package com.example.neoj.config;
import org.neoj.driver.v1.AuthTokens;
import org.neoj.driver.v1.Driver;
import org.neoj.driver.v1.GraphDatabase;
import org.neoj.driver.v1.Session;
import org.springframework.beans.factory. annotation .Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neoj.repository.config.EnableNeo4jRepositories;
import org.springframework. transaction .annotation.EnableTransactionManagement;
@Configuration@EnableNeojRepositories("com.example.neo4j.repository")
@EnableTransactionManagement
public class NeojConfig {    
  @Value("${spring.data.neoj.url}")    
   private  String url;    
  @Value("${spring.data.neoj.username}")  
  private String userName;  
  @Value("${spring.data.neoj.password}")  
  private String password;   
  @Bean(name = "session") 
  public Session neojSession() {  
    Driver driver = GraphDatabase.driver(url, AuthTokens.basic(userName, password));     
    return driver.session();  
  }
} 

4.编写实体类

 package com.example.neoj.entry;
import org.neoj.ogm.annotation.*;
import  Java .util.HashSet;
import java.util.Set;
@NodeEntity("group")
@Datapublic 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 void addRelation(StudentNode sonNode, String name) { 
    RelationEdge relationNode = new RelationEdge(this, sonNode, name);       
    sets.add(relationNode);  
    sonNode.getSets().add(relationNode);  
  }
} 

学生实体类:

 package com.example.neoj.entry;
import org.neoj.ogm.annotation.GeneratedValue;
import org.neoj.ogm.annotation.Id;
import org.neoj.ogm.annotation.NodeEntity;
import org.neoj.ogm.annotation.Relationship;
import java.util.HashSet;
import java.util.Set;
/** 
* 有点类似于Mysql中的table 映射的对象类,mysql中叫做 ORM ,neo4j中叫做OGM [object graph mapping] 
*/@NodeEntity("student")
@Datapublic class StudentNode {    
  @Id    
  @GeneratedValue    
  private Long id;    
  /**     
  * 学生名称    
  */    
  private String name; 
  /**     
  * 性别    
  */    
  private String sex;    
  @Relationship(type = "RelationEdge", direction = "INCOMING")  
  private Set<RelationEdge> sets = new HashSet<>();  
} 
 package com.example.neoj.entry;
import lombok.Data;
import org.neoj.ogm.annotation.*;
@RelationshipEntity(type = "RelationEdge")
@Datapublic 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;   
  }
} 

5.Repository接口

对应的学生接口:

 package com.example.neoj.repository;
import com.example.neoj.entry.StudentNode;
import org.springframework.data.neoj.repository.Neo4jRepository;
public interface StudentRepository  extends  Neo4jRepository<StudentNode,Long> {
} 

对应的班级接口

 package com.example.neoj.repository;
import com.example.neoj.entry.GroupNode;
import org.springframework.data.neoj.repository.Neo4jRepository;
public interface GroupRepository extends NeojRepository<GroupNode,Long> {
} 

最后完成编写我们的 Controller

 package com.example.neoj.controller;
import com.example.neoj.entry.*;
import com.example.neoj.repository.GroupRepository;
import com.example.neoj.repository.StudentRepository;
import lombok.extern.slfj.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation. Request Mapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/node")
@Slfjpublic class GroupController { 
  @Autowired   
  private StudentRepository studentRepository;  
  @Autowired   
  private GroupRepository groupRepository;  
  @GetMapping(value = "/create")  
  public void createNodeRelation() {  
    StudentNode studentNode = new StudentNode(); 
    studentNode.setName("Alen");    
    studentNode.setSex("男");      
    StudentNode studentNode = new StudentNode();
    studentNode.setName("Kai");     
    studentNode.setSex("女");    
    studentRepository.save(studentNode);     
    studentRepository.save(studentNode);    
    GroupNode groupNode = new GroupNode();   
    groupNode.setName("火箭班");   
    groupNode.setNum("");       
    // 增加关系       
    groupNode.addRelation(studentNode, "includes");    
    groupNode.addRelation(studentNode, "includes"); 
    groupRepository.save(groupNode);   
  }
} 

启动之后,访问​ ​​

我们再去图谱数据库看看。

怎么样,使用Java 操作是不是也是非常简单的呢?这样的图谱数据库你会选择么?