spring-data-neo4j remove nodeEntity and all referenced nodes

南笙酒味 提交于 2019-12-11 03:17:58

问题


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:

What I've tried:

  • Delete a user through GraphRepository
  • Delete a user through Neo4jTemplate

In both cases, only User is deleted:

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!


回答1:


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



来源:https://stackoverflow.com/questions/30130275/spring-data-neo4j-remove-nodeentity-and-all-referenced-nodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!