0
votes

In spring data neo4j I have simple one-to-many relationship: (:User)-[:EMPLOYEE_OF]->(:Company). User can be employee of only one company. Here are my entities:

class User(@Relationship(type = "EMPLOYEE_OF") var company: Company? = null, /* ids etc */)
class Company(/* ids etc */)

When I want to change target of that relationship or remove it neo4j keeps adding new relationships instead of replacing it.

val user = userRepository.findByName("user1")
val company = companyRepository.findByName("company1")
user.company = company
userRepository.save(user)

// 2nd case

user.company = null
userRepository.save(user)

In both cases, relationships are only added, never removed. Is there a proper way to do it?

1

1 Answers

1
votes

You have to put the load / find and the save in a transaction. The best way in a Spring project to do this is to extract the logic into a service layer method of your application and mark it as @Transactional.

Within this transaction, Spring Data Neo4j / Neo4j-OGM can track the changes that happen on the node and change or remove the relationships.