最近要做一个关于知识图谱的项目,需要将数据存储到 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);
}
}
}
测试通过
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏