Armen Arzumanyan Armen Arzumanyan - 1 month ago 12
Java Question

How can I update node or node entity in Spring data neo4j?

In Spring data neo44 we have just

repository.save(entity)
, but for example when my UserEntity's property(email) changed, i dont know how to update the same.

I tried also with neo4j template, but save entity with existing node id caused the below rollback.

org.springframework.dao.InvalidDataAccessApiUsageException: New value must be a Set, was: class java.util.ArrayList; nested exception is java.lang.IllegalArgumentException: New value must be a Set, was: class java.util.ArrayList
at org.springframework.data.neo4j.support.Neo4jExceptionTranslator.translateExceptionIfPossible(Neo4jExceptionTranslator.java:43)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)


How we can update node or nodeentity?

public void updateUserNode(UserEntity user) {
try{
UserEntity updatedUser = this.getUserByUserId(user.getUserId());//finding node with user id///
updatedUser.setEmail(user.getEmail());
updatedUser.setImageId(user.getImageId());
updatedUser.setFirstname(user.getFirstname());
updatedUser.setLastname(user.getLastname());
//System.out.println("Deleting ");
//userRepository.delete(del);
System.out.println("UPDATING ");
// with existing Id, you can not save it again/, or update
updatedUser = userRepository.save(updatedUser);
}catch(Exception e){
e.printStackTrace();
}
//return
}

Answer

You have to embed the .save() within a transaction.

As an example:

final org.neo4j.graphdb.Transaction tx = this.neoTemplate.getGraphDatabaseService().beginTx();
try {
    updatedUser = userRepository.save(updatedUser);
    tx.success();
} finally {
    tx.finish();
}