Search code examples
neo4jpass-by-referencespring-data-neo4j-4neo4j-ogm

Spring Data Neo4j overwrites attributes


I tried writing a service, having an update(User) function using SDN 4.0.0. The function should look, it there is a User in the database with the same id, and if so, overwrite this user with the new one.

Having a UserRepository which extends the GraphRepository<User> I wrote the following code:

User updateUser(User user){
  if(userRepository.findOne(user.getId())!=null){
    user = userRepository.save(user);
    return user;
  }else{
    //Exception handling here
  }
}

I now have the problem, that each user I update stays the way it was in the database because from the moment, the findOne(id) is called, all attributes of the user object get overwritten with the user as it is in the database.

I already fixed the problem, by adding an existsById(Long id) function in the repository annotated with the Query "Match (n:User) where ID(n)={0}".

However, I'm still interested, why SDN overwrites an object having the same id as an object i tried to get. I'm assuming there a references involved, but i can't really see the advantages of it.


Solution

  • This is by design, that when you load an entity from the database, it is the most recent version in the graph, thus overwriting any unsaved changes.

    If you change the order of operations- load first, if it exists, then modify and save- you should be fine.