spring-boot - 如何使用 Neo4j 在 Spring-boot 项目中设置实体?
问题描述
心里有个想法:如果我使用Spring Boot构建基于Neo4j的项目,需要提前定义好Entity的属性和方法。如果我以后想在图中添加新的边或属性,甚至是新类型的节点,我应该如何处理实体?
解决方案
您可以通过以下方式编写实体
示例实体代码:
package com.example.accessingdataneo4j;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
@NodeEntity
public class Person {
@Id @GeneratedValue private Long id;
private String name;
private Person() {
// Empty constructor required as of Neo4j API 2.0.5
};
public Person(String name) {
this.name = name;
}
/**
* Neo4j doesn't REALLY have bi-directional relationships. It just means when querying
* to ignore the direction of the relationship.
* https://dzone.com/articles/modelling-data-neo4j
*/
@Relationship(type = "TEAMMATE", direction = Relationship.UNDIRECTED)
public Set<Person> teammates;
public void worksWith(Person person) {
if (teammates == null) {
teammates = new HashSet<>();
}
teammates.add(person);
}
public String toString() {
return this.name + "'s teammates => "
+ Optional.ofNullable(this.teammates).orElse(
Collections.emptySet()).stream()
.map(Person::getName)
.collect(Collectors.toList());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
边缘或关系可以通过以下方式完成
@Relationship(type = "TEAMMATE", direction = Relationship.UNDIRECTED)
public Set<Person> teammates;
在这里,人 [Node] 连接到另一个节点 [team-mates] 并存储。
无论您在哪里设计,都可以添加新类并编写模式并启动服务器。
要执行 CRUD 操作,您可以使用 Spring data jpa Repository。
PersonRepository 扩展了 GraphRepository 接口并插入了它操作的类型:Person。该接口带有许多操作,包括标准的 CRUD(创建、读取、更新和删除)操作。