SpringBoot 接入 Neo4j 数据库

avatar 2024年01月25日12:34:20 0 559 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此

最近要做一个关于知识图谱的项目,需要将数据存储到 Neo4j 图数据库中,然后用 SpringBoot和Vue搭建项目来进行展示。

本文介绍SpringBoot和Neo4j对接,先展示一张表的使用。

一、引入依赖

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

 

二、实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Property;

import java.io.Serializable;

/**
 * @author 言曌 liuyanzhao.com
 * @since 2024/1/22 18:59
 */
@Data
@NodeEntity(label = "person")
@AllArgsConstructor
@NoArgsConstructor
public class Person implements Serializable {


    @Id
    @GeneratedValue
    private Long id;
    @Property
    private String name;

    public Person(String name) {
        this.name = name;
    }

}

 

三、数据访问层

import com.example.neo4jdemo1.entity.Person;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.stereotype.Repository;

/**
 * @author 言曌 liuyanzhao.com
 * @since 2024/1/22 19:02
 */
@Repository
public interface PersonRepository extends Neo4jRepository<Person, Long> {
}

 

四、配置文件 application.properties

# 应用服务 WEB 访问端口
server.port=8080

spring.data.neo4j.uri=bolt://localhost:7687
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=12345678

 

五、单元测试和演示

import com.example.neo4jdemo1.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author 言曌 liuyanzhao.com
 * @since 2024/1/22 19:05
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = com.example.neo4jdemo1.Neo4jDemo1Application.class)
public class PersonRepositoryTest {
    @Autowired
    private PersonRepository personRepository;

    @Test
    public void testCreate() {
//        Optional<Person> byId = personRepository.findById(8L);
//        byId.orElse(null);

        personRepository.save(new Person(5L, "猪八戒啊"));
        personRepository.save(new Person( "王母娘娘"));
        personRepository.save(new Person( "玉皇大帝"));

        Iterable<Person> peopleIterable = personRepository.findAll();
        for (Person person : peopleIterable) {
            System.out.println(person);
        }
    }
}

 

测试通过

 

  • 微信
  • 交流学习,服务定制
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0