spring-data-neo4j删除nodeEntity和所有引用的节点

时间:2015-05-08 18:12:06

标签: java neo4j cypher spring-data spring-data-neo4j

我有一个简单的图表模型: 1 User N SocialUser

我想知道在删除spring-data-neo4j实体时,SocialUser是否有任何方法可以自动删除所有引用的User

这是我到目前为止所得到的:

@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;
}

数据

After insert

我尝试过的事情:

在这两种情况下,只删除User

enter image description here

目前,我已在@Transactional服务的User方法中封装了两个实体的删除。像这样:

   @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);
   }

但我认为这可能不是实现它的最好方法。我还认为直接执行Cypher语句删除所有引用的节点可能会更好。

任何人都可以建议我如何处理这个问题?任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:3)

我知道已经有一段时间了,但在使用1 => {:ok, 2} 2 => {:exit, {:badarith, [{:elixir_compiler_0, :"-__FILE__/1-fun-0-", 1, [file: 'a.exs', line: 8]}, {Task.Supervised, :do_apply, 2, [file: 'lib/task/supervised.ex', line: 94]}, {Task.Supervised, :reply, 5, [file: 'lib/task/supervised.ex', line: 45]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 247]}]}} 3 => {:ok, 6} 4 => {:exit, {%RuntimeError{message: "I don't like 4!"}, [{:elixir_compiler_0, :"-__FILE__/1-fun-0-", 1, [file: 'a.exs', line: 9]}, {Task.Supervised, :do_apply, 2, [file: 'lib/task/supervised.ex', line: 94]}, {Task.Supervised, :reply, 5, [file: 'lib/task/supervised.ex', line: 45]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 247]}]}} 5 => {:ok, 10} 6 => {:ok, 12} 7 => {:ok, 14} 8 => {:ok, 16} 9 => {:ok, 18} 10 => {:ok, 20} SDN之后,似乎最好的方法是使用neo4j查询。

Cypher

使用SDN,我们可以利用repositores:

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

希望它可以帮助其他人