简体   繁体   中英

Neo4j save @Relationship data

Here's MVCE: https://github.com/neo4j-examples/movies-java-spring-data-neo4j If you change one test to:

@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());
}

You can see in debug mode that object p does not have any movies .

Person entity is:

@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;
    }
}

This is offical example from neo4j. How can i store entity Person with movies in database and also have Movie entity with roles ?

Edit: What i can do is add in Person entity method:

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

And in the test add:

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

But i don't like this - cause i setting it manually from two sites.

You do not need to set the references manually from two sides. Expand your code snippet slightly by a single line movie.setPerson(this); and you are done:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM