Tyler
Tyler

Reputation: 383

Why is my modified neo4j node property not persisted to the db?

I'm using Spring Data Neo4J 3.3.1 and I'm having difficulty updating nodes. I have code equivalent to this, and it has zero impact on the database:

@Transactional
public void editTitle(Long nodeId, String newTitle) {
    MyNode existingNode = nodeRepository.findOne(nodeId);
    existingNode.getSubObject().setTitle(newTitle);
    nodeRepository.save(existingNode);
}

This is the MyNode class:

@NodeEntity
public class MyNode {

    @Fetch
    @RelatedTo(type="LINKED_TO", direction = Direction.OUTGOING)
    private SubObject subObject;

    public SubObject getSubObject() {
        return subObject;
    }
}

This is the SubObject class:

@NodeEntity
public class SubObject {

    private String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

I am able to save new nodes of type MyNode without a problem. I simply call nodeRepository.save(newNode); and it saves the MyNode AND the SubObject to the database at once.

I have confirmed that the transaction is being committed. I've followed the call stack all the way down to the NeoStoreTransaction class and observed the executeModified method processing a command, but the field I changed is not represented there.

Upvotes: 0

Views: 55

Answers (1)

Tyler
Tyler

Reputation: 383

For edits, you will need to save related nodes explicitly:

@Transactional
public void editTitle(Long nodeId, String newTitle) {
    MyNode existingNode = nodeRepository.findOne(nodeId);
    existingNode.getSubObject().setTitle(newTitle);
    subObjectRepository.save(existingNode.getSubObject());
    nodeRepository.save(existingNode);
}

That's because the save operation treats related nodes differently depending on whether they have already been persisted to the database.

  • For cases where the related node has not been persisted yet, the related node will be saved automatically.
  • For cases where the related node has already been persisted, e.g. when you're coming back later to make an edit, changes to properties on the related node will NOT be picked up.

Upvotes: 1

Related Questions