gpt4 book ai didi

java - Neo4j保存@Relationship数据

转载 作者:行者123 更新时间:2023-12-02 02:36:01 26 4
gpt4 key购买 nike

这是 MVCE:https://github.com/neo4j-examples/movies-java-spring-data-neo4j如果您将一项测试更改为:

@Test
public void testFindByTitle() {
String title = "The Matrix";
Movie result = movieRepository.findByTitle(title);

Person p = personRepository.findByName("Keanu Reeves");

assertNotNull(result);
assertEquals(1999, result.getReleased());
}

您可以在 Debug模式下看到对象p没有任何电影

Person 实体是:

@NodeEntity
public class Person {

@Id
@GeneratedValue
private Long id;
private String name;
private int born;

@Relationship(type = "ACTED_IN")
private List<Movie> movies = new ArrayList<>();

public Person() {
}

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

public Long getId() {
return id;
}

public String getName() {
return name;
}

public int getBorn() {
return born;
}

public List<Movie> getMovies() {
return movies;
}
}

这是 neo4j 的官方示例。如何在数据库中存储带有 movies 的实体 Person 并同时拥有带有 rolesMovie 实体?

编辑:我能做的是添加Person实体方法:

public void addMovie(Movie movie) {
if (this.movies == null) {
this.movies = new ArrayList<>();
}
this.movies.add(movie);
}

并在测试中添加:

p.addMovie(matrix);
personRepository.save(p);

但我不喜欢这个 - 因为我从两个站点手动设置它。

最佳答案

您不需要从两侧手动设置引用。将代码片段稍微扩展一行 movie.setPerson(this); 就完成了:

  public void addMovie(@NotNull Movie movie) {
if (this.movies == null)
this.movies = new ArrayList<>();

this.movies.add(movie);
movie.setPerson(this);
}

关于java - Neo4j保存@Relationship数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57201995/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com