如何使用Neo4j在Spring启动项目中设置实体



我有一些想法:如果我使用Spring Boot构建基于Neo4j的项目,我需要提前定义实体的属性和方法。如果我以后想向图形添加新的边或属性,甚至是新类型的节点,我应该如何处理实体?

关于引用Spring数据-Neo4j Docs

可以用以下方式编写实体

示例实体代码:

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;

在这里,人[节点]连接到另一个节点[队友]并存储。

无论在哪里设计,都可以添加新的类、编写模式并启动服务器。

要执行CRUD操作,可以使用Spring数据jpa存储库。

PersonRepository扩展了GraphRepository接口,并插入了它操作的类型:Person。该接口包含许多操作,包括标准的CRUD(创建、读取、更新和删除(操作。