Search code examples
neo4jspring-data-restspring-data-neo4jspring-data-neo4j-4

spring data rest with neo4j: How to remove relationship


I'm trying to create an example how to remove an relationship at neo4j using spring data rest service. You can use neo4j-movies-example to test.

If I get information about person 1 I see there is one film

curl -s http://localhost:8080/persons/1
{
  "name" : "Keanu Reeves",
  "born" : 1964,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "person" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "movies" : {
      "href" : "http://localhost:8080/persons/1/movies"
    }
  }
}

After changing the entity there is still the relation:

curl -s -X PUT -H "Content-Type:application/json" -d '{ "name" : "Keanu Reeves", "born":1964, "movies": [] }' http://localhost:8080/persons/1
{
  "name" : "Keanu Reeves",
  "born" : 1964,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "person" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "movies" : {
      "href" : "http://localhost:8080/persons/1/movies"
    }
  }
}

Even curl -s -X DELETE http://localhost:8080/persons/1/movies has no effect. So how can I delete a relationship at neo4j with spring-data-rest?

[Update 1] I tried to track it down, but ended in this Issue -> Fixed, was a problem with HashSet and HashCode-Method.

[Update 2] Created an example which shows that Neo4j-OGM works fine, but Spring Data makes trouble. -> Fixed - The problem was a missing @Transactional, so every time a repository was called, a new transaction and session was created. For the update the load and save must be in the same transaction.

[Update 3] After fixed the other issues, I'm able to understand the problem. In a PATCH-Request the object is loaded in a different session then the save-method. The behaviour is as followed the object is load in session[412], the object is manipulated in expected way and then object is save in session[417].


Solution

  • There is a settings to enable the OpenSessionInViewInterceptor in Spring Boot application.properties:

    spring.data.neo4j.open-in-view=true
    

    This works only for regular controllers, not Spring Data REST resources.

    You can provide following configuration to enable the interceptor for Spring Data REST (in any @Configuration class):

    @Bean
    public OpenSessionInViewInterceptor openSessionInViewInterceptor() {
        return new OpenSessionInViewInterceptor();
    }
    
    @Bean
    public MappedInterceptor myMappedInterceptor() {
        return new MappedInterceptor(new String[]{"/**"}, openSessionInViewInterceptor());
    }