troig troig - 1 month ago 12
Java Question

spring-data-neo4j remove nodeEntity and all referenced nodes

I've got a simple graph model: 1

User
has N
SocialUser
.

I'm wondering if there is any way through
spring-data-neo4j
to automatically delete all
SocialUser
referenced when I remove an
User
entity.

This is what I've got so far:

Domain:

@NodeEntity
public class User implements IdentifiableEntity<String> {

@GraphId
private Long nodeId;
// ...

@RelatedTo(type = "HAS", direction = Direction.OUTGOING)
Set<SocialUser> socialUsers = new HashSet<>();
}

@NodeEntity
public class SocialUser implements BasicNodeEntity {

@GraphId
private Long nodeId;
//...

@RelatedTo(type = "HAS", direction = Direction.INCOMING)
User user;
}


Data:

After insert

What I've tried:



In both cases, only
User
is deleted:

enter image description here

At the moment I've encapsulated the deletion of both entities in a
@Transactional
method in the
User
service. Something like this:

@Autowired
Neo4jOperations template;

@Transactional
public void delete(String userId) throws Exception {
User user = get(userId);
if (user == null) throw new ResourceNotFoundException("user not found");
Set<SocialUser> socialUsers = template.fetch(user.getSocialUsers());
for (SocialUser socialUser : socialUsers) template.delete(socialUser);
userRepository.delete(user);
}


But I'm thinking it's probably not the best way to achieve it. Also I've thought that it could be better to directly execute a
Cypher
statement to delete all referenced nodes..

Anyone can advise me how to deal with this? Any help would be greatly appreciated. Thanks!

Answer

I know it's been a while, but after being a time working with SDN and neo4j, it seems to be that the best way to accomplish this is using a Cypher query.

MATCH (user:User{id:'userId'})-[has:HAS]->(socialUser:SocialUser)
DELETE user, has, socialUser

With SDN, we can take advantadge of repositores:

@Repository
public interface UserRepository extends Neo4jRepository<User> {

    @Query("MATCH (user:User{id:{id}})-[has:HAS]->(socialUser:SocialUser) DELETE user, has, socialUser")
    void delete(String id);
}

Hope it helps other people